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);
            
            
        }
    }
  • 相关阅读:
    Java抽象类和接口和继承之间关系
    Java程序中解决数据库超时与死锁
    怎样成为一名出色的Java Web程序员?
    Java中断线程的方法
    Java 集合框架(Collection)和数组的排序
    StringBuffer帮你减轻Java的负担
    学好Java开发的关键七步
    kvm的分层控制
    一个高扩展高可用高负载的应用架构的诞生记(原创)
    防火墙规则
  • 原文地址:https://www.cnblogs.com/frankcui/p/10480402.html
Copyright © 2011-2022 走看看