|
3 | 3 | * @return {number}
|
4 | 4 | */
|
5 | 5 | const rob = (nums) => {
|
| 6 | + if (1 === nums.length) return nums[0]; |
6 | 7 |
|
| 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]]); |
7 | 23 | };
|
8 | 24 |
|
| 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 | + |
9 | 65 | // [2,3,2] // 3
|
10 | 66 | // [1,2,3,1] // 4
|
11 | 67 | // [1,2,3] // 3
|
0 commit comments