Skip to content

Commit 0d503eb

Browse files
committed
Merge branch '95-daily-29일차'
2 parents a59af96 + b4a29a4 commit 0d503eb

File tree

2 files changed

+36
-0
lines changed

2 files changed

+36
-0
lines changed
Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
var rob = function (nums) {
2+
const len = nums.length;
3+
4+
let arr = new Array(len);
5+
arr[0] = nums[0];
6+
arr[1] = Math.max(nums[0], nums[1]);
7+
let i;
8+
for (i = 2; i < len; i++) {
9+
arr[i] = Math.max(arr[i - 1], arr[i - 2] + nums[i]);
10+
}
11+
12+
return arr[len - 1];
13+
};
14+
15+
console.log(rob([2, 1]));
16+
17+
// DP
Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
var rob2 = function (nums) {
2+
const getMax = (nums) => {
3+
let prevRob = 0,
4+
maxRob = 0;
5+
6+
for (let num of nums) {
7+
let temp = Math.max(maxRob, prevRob + num);
8+
prevRob = maxRob;
9+
maxRob = temp;
10+
}
11+
12+
return maxRob;
13+
};
14+
15+
if (nums.length === 1) return nums[0];
16+
return Math.max(getMax(nums.slice(0, -1)), getMax(nums.slice(1)), nums[0]);
17+
};
18+
19+
console.log(rob2([1, 2, 3, 1]));

0 commit comments

Comments
 (0)