zoukankan      html  css  js  c++  java
  • [leetcode] 198. House Robber I

    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.

    题目给出一个数组,代表一排房子,数值代表该房子能偷得的金额;当相邻的两个房子被偷时,就会触发自动报警,问小偷在不触发自动报警的前提下能偷到的最大金额。
    class Solution {
        public int rob(int[] nums) {
            //共有n家
            int n = nums.length;
            if(n == 0){
                return 0;
            }
            //res[i]表示到第i家止,可以劫到最多的钱
            int[] res = new int[n + 1];
            res[0] = 0;
            res[1] = nums[0];
            
            for(int i=2; i<n+1; i++){
                //劫到第i家能劫得最多的钱,
                //1.劫第i家,则说明没劫第i-1家,则此时最多为劫到第i-2家的最多前+第i家的前 = res[i-2] + nums[i-1]
                //2.不劫第i家,则劫得最多的钱为劫到第i-1家得到的最多前 res[i-1]
                res[i] = Math.max(res[i-2] + nums[i-1], res[i-1]);
            }
            
            return res[n];
                
        }        
    }
    

      

  • 相关阅读:
    杂想
    验证码再次学习。(处理方法汇总)
    神经网络学习入门 -01
    基于本地文字提取的有效的定位和识别场景文字
    C#学习总结~~~
    Deep Learning!!!
    记事本也能批量更名
    家庭一台电脑多人上网方法
    基于 OS X Mavericks 系统
    关于中文编程是解决中国程序员效率的秘密武器的问题思考
  • 原文地址:https://www.cnblogs.com/zebinlin/p/9802828.html
Copyright © 2011-2022 走看看