Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit c8183ea

Browse files
authored
Create 1463-cherry-pickup-ii.js
solved cherry-pickup-ii
1 parent 822c53a commit c8183ea

File tree

1 file changed

+41
-0
lines changed

1 file changed

+41
-0
lines changed

javascript/1463-cherry-pickup-ii.js

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
/**
2+
* 2D-DP | Memoization
3+
* Time O(n^3) | Space O(n^3);
4+
* https://leetcode.com/problems/cherry-pickup-ii/
5+
* @param {number[][]} grid
6+
* @return {number}
7+
*/
8+
var cherryPickup = function(grid) {
9+
10+
const ROW = grid.length;
11+
const COL = grid[0].length;
12+
const cache = new Map();
13+
14+
const columnOutOfBound = (c) => {
15+
if (c < 0) return true;
16+
if (c === COL) return true;
17+
return false;
18+
}
19+
20+
const dfs = (r1, c1, c2) => {
21+
22+
const hash = `${r1}-${c1}-${c2}`;
23+
if (cache.has(hash)) return cache.get(hash);
24+
if (columnOutOfBound(c1) || columnOutOfBound(c2)) return 0;
25+
if (r1 === ROW) return 0;
26+
27+
const currTwoRobotSum = grid[r1][c1] + (c1 !== c2 && grid[r1][c2] || 0)
28+
29+
let max = 0;
30+
for (let i = c1-1; i < c1+2; i++) {
31+
for (let j = c2-1; j < c2+2; j++) {
32+
max = Math.max(max, currTwoRobotSum + dfs(r1+1, i, j));
33+
}
34+
}
35+
36+
cache.set(hash, max);
37+
return max;
38+
}
39+
40+
return dfs(0,0, COL-1);
41+
};

0 commit comments

Comments
 (0)