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];
                
        }        
    }
    

      

  • 相关阅读:
    表单全选,不选和反选
    利用js改变宽,高等属性
    点击显示与隐藏
    改变div的不同属性
    给三个不同的div变色
    经典排序算法实现
    基本排序算法的实现
    排序的概念及分类实现
    #和##运算符实例
    #pragma预处理实例
  • 原文地址:https://www.cnblogs.com/zebinlin/p/9802828.html
Copyright © 2011-2022 走看看