Skip to content

Commit 2bc6716

Browse files
committed
Update house-robber.js
1 parent c09ae11 commit 2bc6716

1 file changed

Lines changed: 34 additions & 0 deletions

File tree

leetcode/house-robber.js

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1 +1,35 @@
1+
//动态规划的题
12

3+
/**
4+
* Question:
5+
* You are a professional robber planning to rob houses along a street.
6+
* Each house has a certain amount of money stashed,
7+
* the only constraint stopping you from robbing each of them is that adjacent houses have security system connected
8+
* and it will automatically contact the police
9+
* if two adjacent houses were broken into on the same night.
10+
11+
* Given a list of non-negative integers representing the amount of money of each house,
12+
* determine the maximum amount of money you can rob tonight without alerting the police.
13+
*
14+
* /
15+
16+
17+
/**
18+
* @param {number[]} nums
19+
* @return {number}
20+
*/
21+
var rob = function(nums) {
22+
var currMaxPV = 0, //当前最大值:上一轮循环中的最大值加上当前值
23+
lastRealMax = 0, //上一轮循环中的真正的最大值
24+
i = nums.length -1,
25+
tempLastMaxPV, //
26+
realLastMax;
27+
while ( 0 <= i) { // eg: [2,1,1,2]
28+
tempLastMaxPV = currMaxPV; //2 0 3
29+
realLastMax = lastRealMax; //0 2 2
30+
currMaxPV = realLastMax + nums[i];//1 3 4
31+
lastRealMax = tempLastMaxPV > realLastMax ? tempLastMaxPV :realLastMax;//2 2 3
32+
i--;
33+
}
34+
return currMaxPV > lastRealMax ? currMaxPV : lastRealMax;
35+
};

0 commit comments

Comments
 (0)