-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0741-cherry-pickup.js
More file actions
91 lines (79 loc) · 2.69 KB
/
0741-cherry-pickup.js
File metadata and controls
91 lines (79 loc) · 2.69 KB
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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
/**
* Cherry Pickup
* Time Complexity: O(N^3)
* Space Complexity: O(N^3)
*/
var cherryPickup = function (grid) {
const gridDimension = grid.length;
const memoTable = Array.from({ length: gridDimension }, () =>
Array.from({ length: gridDimension }, () =>
new Array(2 * gridDimension - 1).fill(-Infinity),
),
);
if (grid[0][0] === -1) {
return 0;
}
memoTable[0][0][0] = grid[0][0];
for (
let currentStep = 1;
currentStep < 2 * gridDimension - 1;
currentStep++
) {
for (let firstPersonX = 0; firstPersonX < gridDimension; firstPersonX++) {
const firstPersonY = currentStep - firstPersonX;
if (firstPersonY < 0 || firstPersonY >= gridDimension) {
continue;
}
if (grid[firstPersonX][firstPersonY] === -1) {
continue;
}
for (
let secondPersonX = 0;
secondPersonX < gridDimension;
secondPersonX++
) {
const secondPersonY = currentStep - secondPersonX;
if (secondPersonY < 0 || secondPersonY >= gridDimension) {
continue;
}
if (grid[secondPersonX][secondPersonY] === -1) {
continue;
}
let maximumPreviousCherries = -Infinity;
const firstPersonPrevXOptions = [firstPersonX - 1, firstPersonX];
const secondPersonPrevXOptions = [secondPersonX - 1, secondPersonX];
for (const potentialFirstPersonPrevX of firstPersonPrevXOptions) {
for (const potentialSecondPersonPrevX of secondPersonPrevXOptions) {
if (
potentialFirstPersonPrevX >= 0 &&
potentialSecondPersonPrevX >= 0
) {
const previousStateCherries =
memoTable[potentialFirstPersonPrevX][
potentialSecondPersonPrevX
][currentStep - 1];
if (previousStateCherries > -Infinity) {
maximumPreviousCherries = Math.max(
maximumPreviousCherries,
previousStateCherries,
);
}
}
}
}
if (maximumPreviousCherries === -Infinity) {
continue;
}
let currentCherriesCollected = grid[firstPersonX][firstPersonY];
if (firstPersonX !== secondPersonX || firstPersonY !== secondPersonY) {
currentCherriesCollected += grid[secondPersonX][secondPersonY];
}
memoTable[firstPersonX][secondPersonX][currentStep] =
maximumPreviousCherries + currentCherriesCollected;
}
}
}
const finalAccumulatedCherries =
memoTable[gridDimension - 1][gridDimension - 1][2 * gridDimension - 2];
return finalAccumulatedCherries < 0 ? 0 : finalAccumulatedCherries;
};