[JS][dp] Problem Solution | #Family Robbery (1)#

Solution | #Family Robbery (1)#


topic link

robbery (1)

Topic description

describe

You are an experienced thief, ready to steal a row of rooms along the street, each room has a certain amount of cash, in order to prevent detection, you cannot steal the adjacent two, that is, if you steal the first one, you will The second house cannot be stolen; if the second house is stolen, then the first and the third house cannot be stolen.
Given an integer array nums, the elements in the array represent the amount of cash in each room, please calculate the maximum amount of theft without being found.

alt

Example 1

enter:

[1,2,3,4]

return value:

6

illustrate:

The best solution is to steal the 2nd and 4th rooms

Example 2

enter:

[1,3,6]

return value:

7

illustrate:

The best solution is to steal the 1st and 3rd rooms

Example 3

enter:

[2,10,5]

return value:

10

illustrate:

The best solution is to steal the second room


Problem solving ideas

Simple dp, there are only two types of stealing for each room, you are a thief, and you do not know how many are behind.

When we visit room i, we have only two options: steal i, and pick up i-2 and all previous wealth; not steal i, pick up i-1 and all previous wealth. We can guarantee that we will get the most money when we visit the i-th room.

This is a good solution, just use an array to store the accumulated number, and the last most wealth value is the value of the last item of the array.


answer

//打家劫舍(一)
function rob(nums) {
    
    
    // write code here
    let stealList = [];
    let max = 0;
    stealList[0] = nums[0];
    stealList[1] = nums[0] > nums[1] ? nums[0] : nums[1];
    for (let i = 2; i < nums.length; i++) {
    
    
        let s = stealList[i - 2] + nums[i];
        if (stealList[i - 1] > s)
            s = stealList[i - 1];
        stealList[i] = s;
    }
    return stealList[nums.length - 1];
}
console.log(rob([1, 2, 3, 4]));
module.exports = {
    
    
    rob: rob
};

Guess you like

Origin blog.csdn.net/qq_36286039/article/details/123276907