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

      

  • 相关阅读:
    Python 中多线程之 _thread
    Python ftplib 模块关于 ftp的下载
    nessus 漏洞扫描安装和使用
    实战medusa暴力破解
    浅谈python 中正则的一些函数
    一句话木马和中国菜刀的结合拿webshell
    浅说套接字socket做个小小的监控
    小巧的ssh客户端
    统计字符串的数字,英文字母,空格及其他的个数
    mysql字符串函数
  • 原文地址:https://www.cnblogs.com/zebinlin/p/9802828.html
Copyright © 2011-2022 走看看