[LeetCode-Dynamic Programming] Fighting Home II

Title description

You are a professional thief and plan to steal houses along the street, each room contains a certain amount of cash. All houses in this place are in a circle, which means that the first house and the last house are next to each other. At the same time, the neighboring houses are equipped with an interconnected anti-theft system. If two neighboring houses are broken into by a thief on the same night, the system will automatically call the police.
Given a non-negative integer array representing the amount of money stored in each house, calculate the maximum amount you can steal without touching the alarm device.
Examples:

输入: [2,3,2]
输出: 3
解释: 你不能先偷窃 1 号房屋(金额 = 2),然后偷窃 3 号房屋(金额 = 2), 因为他们是相邻的。

输入: [1,2,3,1]
输出: 4
解释: 你可以先偷窃 1 号房屋(金额 = 1),然后偷窃 3 号房屋(金额 = 3)。
     偷窃到的最高金额 = 1 + 3 = 4 。

Link to the title : https://leetcode-cn.com/problems/house-robber-ii/
Before doing this question, you can first do some home robbery .

Ideas

Because it is circular, the first house and the last house cannot appear at the same time, so do two dynamic planning, the scope of the first dynamic planning does not include the last house, the scope of the second dynamic planning does not include the first For each house, take the larger of the two dynamic planning results as the answer. code show as below:

class Solution {
public:
    int rob(vector<int>& nums) {
        if(nums.empty()) return 0;
        if(nums.size()==1) return nums[0];  // 注意只有一个房屋的情况

        return max(doRub(nums, 0, nums.size()-2), doRub(nums, 1, nums.size()-1));
    }

    int doRub(vector<int> nums, int left, int right){
        int dp[nums.size()];
        memset(dp, 0, sizeof(dp));
        dp[left] = nums[left];
        for(int i=left+1; i<=right; i++){
            if(i==left+1){
                dp[i] = max(nums[left], nums[left+1]);
            }else{
                dp[i] = max(dp[i-2]+nums[i], dp[i-1]);
            }
        }
        return dp[right];
    }
};
  • Time complexity: O (n)
  • Space complexity: O (n)

Guess you like

Origin www.cnblogs.com/flix/p/12733379.html