[LeetCode] 198. House Robber Java

來源:互聯網
上載者:User

標籤:from   automatic   list   size   bsp   數組   represent   lan   style   

題目:

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.

 

題意及分析:給出一個非負的數組,從頭到尾遍曆,求取一個能得到最大和的序列,其中每兩個元素不能相鄰。使用動態規劃,到當前元素i的最大收益只有兩種情況:

(1)前一個元素得到最大值

(2)從前一個元素的前一個元素加上當前元素得到最大值

比較兩個值,取最大值為當前點的最大收益

 

代碼:

 

public class Solution {    public int rob(int[] nums) {        int max=Integer.MIN_VALUE;                int length=nums.length;        if(length==0)        return 0;        if(length==1)        return nums[0];        if(length==2)        return Math.max(nums[0], nums[1]);        int[] res = new int[length];        res[0]=nums[0];        res[1]=Math.max(nums[0], nums[1]);        max=Math.max(nums[0], nums[1]);        for(int i=2;i<length;i++){        max=Math.max(res[i-2]+nums[i], res[i-1]);        res[i]=max;        }        return res[length-1];    }}

 

  

 

[LeetCode] 198. House Robber Java

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.