leetcode 213. loot II: dynamic programming (c ++)

  • leetcode 213. loot II

    You are a professional thief to steal street plan of the house, each room are in possession of some cash. This place all the houses are in a circle, which means that the first and the last house is next to the house. Meanwhile, neighboring houses equipped with anti-theft system communicate with each other, if two adjacent houses on the same night, thieves broke into the system will automatically alarm.

    Given a representative from each non-negative integer array of Housing storage amount calculated in case you do not touch the alarm device, can steal the maximum amount to.

    Example:

    Input: [2, 3, 2]

    Output: 3

    Explanation: You can not steal first No. 1 Housing (amount = 2), and then steal the 3rd house (money = 2), because they are adjacent.

  • analysis

    The problem is leetcode 198. robbery expansion, using a cyclic permutation, it may be modified based on title 198, in two steps:

    • Not steal first: From [1 .... n-1] is obtained a maximum value
    • The first steal: from [0 .... n-1] is obtained a maximum value

    Dp specific ideas:

    1. Status and stage design: dp [i] indicates the maximum value before the home i obtained
    2. State transition:
      1. When the i-th not steal: dp [i] = dp [i - 1]
      2. When the i-th steal: dp [i] = dp [i - 2] + nums [i]
      3. It is worth noting: When the i-th analyzed, we do not know the first i - 1 home if stolen:
        1. When the first i - 1 family did not stolen, then dp [i] = dp [i - 1] + nums [i], but this time dp [i - 1] = dp [i - 2], to obtain DP [ i] = dp [i - 2] + nums [i]
        2. When the first i - 1 home stolen, the dp [i] = dp [i - 1] + nums [i] is not desirable, i.e., dp [i] = dp [i - 1]
      4. Transfer sum equation: dp [i] = max (dp [i - 1], dp [i - 2] + nums [i])
    3. Borders: Add borders dp [0] = 0 does not exist, a front grab 0 0
  • Code

    Note that considering the length of the input array obtained where 0

    class Solution {
    public:
        int rob(vector<int>& nums) {
            int n = nums.size();
    
            if(n == 0) return 0;
    
            //int ans=0;
            int dp[n + 1];
            dp[0] = 0;          //第0间
    
            //不偷第一间
            dp[1] = 0;
            int ans = nums[0];
            for(int i = 2; i <= n; ++i) {
                dp[i] = max(dp[i - 2] + nums[i - 1], dp[i - 1]);
                ans = max(ans, dp[i]);
            }
    
            //偷第一间
            dp[1] = nums[0];
            for(int i = 2; i < n; ++i) {
                dp[i] = max(dp[i - 2] + nums[i - 1], dp[i - 1]);
                ans = max(ans, dp[i]);
            }
    
            return ans;
        }
    };

Guess you like

Origin www.cnblogs.com/joe-w/p/12325439.html