LeetCode198. Robbery

topic

You are a professional robber planning to rob houses along the street. Each room has a certain amount of cash hidden, and the only constraint preventing you from robbing them is that the adjacent houses have a security system connected, which will automatically contact the police if two adjacent houses are broken into on the same night .

Given a list of non-negative integers representing the amount of money for each house, determine the maximum amount you can rob without alerting the police .


analyze

Simple dynamic programming problem, the title means to calculate the maximum sum of non-adjacent numbers in an array.

For example   [ 1, 3, 4, 5, 3, 2 ]  should return 10 , 3 + 5 + 2 = 10.

The maximum amount that can be grabbed by n houses = max (the maximum amount that can be grabbed by n-1 houses, the maximum amount that can be grabbed by n-2 houses + the amount of the nth house), so use An array to hold the maximum amount of money that can be grabbed for the current house.  

Take the above example to continue to see the specific process

[ 1,      3,      4,     5,     3,       2 ]  

The maximum value corresponding to the current position is:

  1        3       5      8     8        10

Calculation process  : The maximum value corresponding to the first element of the array is itself 1; the maximum value corresponding to the second element is max(1,3) = 3; the maximum value corresponding to the third element is max( 3 , 1+4 ) = 5 ; the maximum value corresponding to the fourth element is max( 5, 3+5 ) = 8 ; the maximum value corresponding to the fifth element is max( 8 , 3+5) = 8; The maximum value corresponding to the sixth element is max(8, 8+2) = 10. So the final result is 1.

Um. . Note that the value of array[1] should be max(nums[0], nums[1]) instead of nums[1]. I made this mistake when I wrote it, and I still can't find it. . .

code

class Solution {
    public int rob(int[] nums) {
        if (nums.length == 0 || nums == null)
            return 0;
        if (nums.length == 1)return nums[0];
        if (nums.length == 2) return nums[0]>nums[1] ? nums[0]:nums[1];
        
        int[] array = new int[nums.length];//Save the maximum number that can be grabbed for each position
        
        for (int i = 0; i < nums.length; i++)
            if (i == 0 ) array[0] = nums[0];
            else if (i == 1 ) array[1] = Math.max(nums[0],nums[1]);
            else array[i] = Math.max(array[i-1], (array[i-2]+nums[i]));

        return array[nums.length-1];
    }
}


Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324690237&siteId=291194637