-
Notifications
You must be signed in to change notification settings - Fork 7
/
1463-Cherry-Pickup-II.js
56 lines (43 loc) · 1.27 KB
/
1463-Cherry-Pickup-II.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
/**
* @param {number[][]} grid
* @return {number}
*/
const cherryPickup = (grid) => {
const columns = grid.length;
const rows = grid[0].length;
const memory = Array(columns + 1).fill(false);
const move = (i = 0, left = 0, right = rows - 1) => {
const name = `${left}-${right}-${i}`;
if (memory[name] > -1) {
return memory[name];
}
if (i === columns) {
return (memory[name] = 0);
}
memory[name] = 0;
for (let p = -1; p <= 1; p++) {
let newLeft = left;
if (i > 0) {
newLeft += p;
}
if (!(0 <= newLeft && newLeft < rows)) {
continue;
}
for (let q = -1; q <= 1; q++) {
let newRight = right;
if (i > 0) {
newRight += q;
}
if (!(0 <= newRight && newRight < rows) || newRight <= newLeft) {
continue;
}
memory[name] = Math.max(
memory[name],
grid[i][newLeft] + grid[i][newRight] + move(i + 1, newLeft, newRight)
);
}
}
return memory[name];
};
return move();
};