• Leetcode 198. House Robber


    URL : https://leetcode.com/problems/house-robber/

    You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed, the only constraint stopping you from robbing each of them is that adjacent houses have security system connected and it will automatically contact the police if two adjacent houses were broken into on the same night.

    Given a list of non-negative integers representing the amount of money of each house, determine the maximum amount of money you can rob tonight without alerting the police.

    Example 1:

    Input: [1,2,3,1]
    Output: 4
    Explanation: Rob house 1 (money = 1) and then rob house 3 (money = 3).
                 Total amount you can rob = 1 + 3 = 4.

    Example 2:

    Input: [2,7,9,3,1]
    Output: 12
    Explanation: Rob house 1 (money = 2), rob house 3 (money = 9) and rob house 5 (money = 1).
                 Total amount you can rob = 2 + 9 + 1 = 12.

    解决方案

    /**
    * 罗列出每天偷Y和不偷N的盈利情况
    * Y(n) =  nums[n] + N(n-1); //前一天肯定不能偷,再加上今天偷的金额
    * N(n) = Max(Y(n-1), N(n-1)); //前一天偷或者不偷均可,选取最大值。因为今天不再偷,所以不必加另外的金额
    * 最后的结果就是Max(Y(n),N(n))...
    */
    
    import java.lang.Math;
    class Solution {
        public int rob(int[] nums) {
            
            if(nums == null || nums.length < 1){
                return 0;
            }
    
            int pre_yes = 0;
            int pre_no = 0;
            
            int cur_yes = 0;
            int cur_no = 0;
            
            for(int i = 0; i < nums.length; ++i){
                cur_yes = nums[i] + pre_no;
                cur_no = Math.max(pre_yes,pre_no);
                
                pre_yes = cur_yes;
                pre_no = cur_no;
            }
            return Math.max(pre_yes,pre_no);
            
            
        }
    }
  • 相关阅读:
    随机ID添加
    学生ID查询
    node.js基础
    冒泡排序
    循环判断语句
    vue.js详细教程--优优优
    final注意事项
    HashMap Hashtable区别
    java中间件
    JSP错误页面
  • 原文地址:https://www.cnblogs.com/frankcui/p/10480402.html
Copyright © 2020-2023  润新知