• 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);
            
            
        }
    }
  • 相关阅读:
    谷歌地球服务器"失联"的替代方案
    Win32Api -- 回到Windows桌面
    WPF -- 应用启动慢问题
    Windows -- 多网卡上网设置
    .Net -- ConfigurationSection的简单使用
    WPF -- 使用RenderTargetBitmap将Canvas保存为图片
    WPF -- 使用当前进程打开自定义文件的一种方式
    WPF源码阅读 -- InkCanvas选中笔迹
    WPF源码阅读 -- InkCanvas选择模式
    WPF -- 使用Blend工具绘制Control样式
  • 原文地址:https://www.cnblogs.com/frankcui/p/10480402.html
Copyright © 2020-2023  润新知