Skip to content

Commit 17a14dd

Browse files
authored
Create Cherry Pickup II.java
1 parent a17462d commit 17a14dd

File tree

1 file changed

+32
-0
lines changed

1 file changed

+32
-0
lines changed

Hard/Cherry Pickup II.java

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
class Solution {
2+
public int cherryPickup(int[][] grid) {
3+
int m = grid.length;
4+
int n = grid[0].length;
5+
Integer[][][] cache = new Integer[m][n][n];
6+
return recurse(0, 0, n - 1, grid, cache);
7+
}
8+
9+
private int recurse(int row, int colOne, int colTwo, int[][] grid, Integer[][][] cache) {
10+
if (colOne < 0 || colOne >= grid[0].length || colTwo < 0 || colTwo >= grid[0].length) {
11+
return 0;
12+
}
13+
if (cache[row][colOne][colTwo] != null) {
14+
return cache[row][colOne][colTwo];
15+
}
16+
int result = 0;
17+
result += grid[row][colOne];
18+
if (colOne != colTwo) {
19+
result += grid[row][colTwo];
20+
}
21+
if (row != grid.length - 1) {
22+
int max = 0;
23+
for (int c1 = colOne - 1; c1 <= colOne + 1; c1++) {
24+
for (int c2 = colTwo - 1; c2 <= colTwo + 1; c2++) {
25+
max = Math.max(max, recurse(row + 1, c1, c2, grid, cache));
26+
}
27+
}
28+
result += max;
29+
}
30+
return cache[row][colOne][colTwo] = result;
31+
}
32+
}

0 commit comments

Comments
 (0)