Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commitbbc7890

Browse files
committed
update houseRobber explaination
1 parent5c8801a commitbbc7890

File tree

1 file changed

+18
-11
lines changed

1 file changed

+18
-11
lines changed

‎Easy/198-houseRobber.js‎

Lines changed: 18 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
/**
2+
* dp[i] = Math.max(dp[i-1], dp[i-2]+num[i-1])
23
*@param {number[]} nums
34
*@return {number}
45
*/
@@ -9,24 +10,30 @@ var rob = function(nums) {
910
// the robber has not robber the ith house yet.
1011
varmaxAmount=[0,nums[0]];
1112
for(vari=2;i<=nums.length;i++){
12-
maxAmount[i]=Math.max(maxAmount[i-1],(maxAmount[i-2]+nums[i-1]));
13+
maxAmount[i]=Math.max(maxAmount[i-1],(maxAmount[i-2]+nums[i-1]));
1314
}
1415

1516
returnmaxAmount.pop();
1617
};
1718

1819
// O(1) space, O(N) time
20+
// when a robber arrives at a houose, he has two options: rob or not rob. We use two variables (rob, notRob)
21+
// to track the maxAmount of these two options for the house the robber arrived, say ith house,
22+
// and find the max amount from these two values. So, when the robber arrives at ith house, if
23+
// he decided to rob current ith house, then the max amount he can rob is i-1 th house's max amount
24+
// of not robbed plus this house's amount (nums[i]). If he decided not to rob current ith house, then
25+
// the max amount he can rob (or has robbed) at current (ith) house is the maximum value between robbed
26+
// not robber at (i-1)th house.
27+
//
1928
varrob=function(nums){
20-
if(nums.length===0)return0;
21-
varprevMax=0;
22-
// the currMax is the money the robber has robbed when the robber arrives at ith house,
23-
// the robber has not robber the ith house yet.
24-
varcurrMax=nums[0];
25-
for(vari=2;i<=nums.length;i++){
26-
vartmp=currMax;
27-
currMax=Math.max(currMax,(prevMax+nums[i-1]));
28-
prevMax=tmp;
29+
varrob=0;
30+
varnotRob=0;
31+
32+
for(vari=0;i<nums.length;i++){
33+
vartmp=rob;
34+
rob=notRobCurrHouse+nums[i];
35+
notRobCurrHouse=Math.max(tmp,notRobCurrHouse);
2936
}
3037

31-
returncurrMax;
38+
returnMath.max(rob,notRobCurrHouse);
3239
};

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp