Skip to content

Commit 5dc5bc0

Browse files
committed
✨ [213] Watched YT explanation & coded myself
1 parent 5492bb6 commit 5dc5bc0

File tree

2 files changed

+85
-0
lines changed

2 files changed

+85
-0
lines changed

213/my_solution.js

+56
Original file line numberDiff line numberDiff line change
@@ -3,9 +3,65 @@
33
* @return {number}
44
*/
55
const rob = (nums) => {
6+
if (1 === nums.length) return nums[0];
67

8+
let l2 = [...nums];
9+
nums.pop();
10+
l2.shift();
11+
let r1 = determineToRob(nums), r2 = determineToRob(l2);
12+
13+
console.log("RES")
14+
console.log(r1 > r2 ? r1 : r2)
15+
16+
return r1 > r2 ? r1 : r2;
17+
// console.log("tmpList")
18+
// console.log(Math.max(...tmpList))
19+
// console.log(tmpList[tmpList.length - 1])
20+
// console.log(Math.max(...[...tmpList, nums[nums.length - 1]]))
21+
22+
// return Math.max(...[...tmpList, nums[nums.length - 1]]);
723
};
824

25+
const determineToRob = (list) => {
26+
let tmpList = [];
27+
for (let i = 0; i < list.length; i++) {
28+
console.log(`------> i:${i}, list[i]:${list[i]}, list[i-2]:${list[i - 2]}`)
29+
if (undefined === list[i - 2]) {
30+
console.log("-2 UNDEFINED")
31+
tmpList.push(list[i]);
32+
continue;
33+
}
34+
35+
console.log("- MAX")
36+
console.log(tmpList)
37+
console.log(tmpList.slice(0, i - 2 + 1)) // inclusive
38+
console.log(Math.max(...tmpList.slice(0, i - 2 + 1))) // inclusive
39+
// console.log(Math.max(tmpList[0], tmpList[i - 2]))
40+
tmpList.push(list[i] + (Math.max(...tmpList.slice(0, i - 2 + 1))))
41+
console.log("tmpList")
42+
console.log(tmpList)
43+
}
44+
45+
console.log("-> MAX")
46+
console.log(Math.max(...[...tmpList, list[list.length - 1]]))
47+
48+
return Math.max(...[...tmpList, list[list.length - 1]]);
49+
}
50+
// rob([1, 2])
51+
// rob([2, 1, 1, 2])
52+
// rob([2, 3, 1, 2, 1, 1, 2])
53+
// rob([2, 7, 9, 3, 1])
54+
// rob([1, 2, 3, 1])
55+
// rob([1, 2, 3])
56+
rob([0])
57+
58+
// [2,1,1,2]
59+
// Use Testcase
60+
// Output
61+
// 3
62+
// Expected
63+
// 4
64+
965
// [2,3,2] // 3
1066
// [1,2,3,1] // 4
1167
// [1,2,3] // 3

213/solution.js

+29
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
/**
2+
* @param {number[]} nums
3+
* @return {number}
4+
*/
5+
const rob = (nums) => {
6+
if (1 === nums.length) return nums[0];
7+
8+
let l2 = [...nums];
9+
nums.pop();
10+
l2.shift();
11+
12+
let r1 = determineToRob(nums), r2 = determineToRob(l2);
13+
14+
return r1 > r2 ? r1 : r2;
15+
};
16+
17+
const determineToRob = (list) => {
18+
let tmpList = [];
19+
for (let i = 0; i < list.length; i++) {
20+
if (undefined === list[i - 2]) {
21+
tmpList.push(list[i]);
22+
continue;
23+
}
24+
25+
tmpList.push(list[i] + (Math.max(...tmpList.slice(0, i - 2 + 1))))
26+
}
27+
28+
return Math.max(...[...tmpList, list[list.length - 1]]);
29+
}

0 commit comments

Comments
 (0)