198.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.

思路:新建一個數組temp[i],長度爲n-1;  temp[i]表示第i個數之前的最大值,取temp[i-1]與nums[i]+temp[i-2]的較大值

          temp[i] = Math.max(temp[i-1],nums[i]+temp[i-2]);  

代碼:

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

result = temp[nums.length-1];
}
return result;
    }
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章