java 動態規劃問題(2)

題目:
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家時所偷的金錢最大額爲temp[i],則有如下關係:

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

算法如下:

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

    public int max(int a,int b){
        return a>b?a:b;
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章