zoukankan      html  css  js  c++  java
  • 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);
            
            
        }
    }
  • 相关阅读:
    fiddler中的HexView的16进制数据转明文
    安卓逆向分析韵达超市app接口及其实现
    安卓逆向分析百世来取app接口及其实现
    安卓逆向-快宝驿站
    安卓逆向-工具篇
    记录celery启动时出现bug
    python微信拼手气红包逻辑
    检测函数运行时间
    Python获取硬件信息(硬盘序列号,CPU序列号)
    sorted&filter&map
  • 原文地址:https://www.cnblogs.com/frankcui/p/10480402.html
Copyright © 2011-2022 走看看