Cherry Pickup

  • 741.Cherry Pickup *
  1. DP problem, but greedy solution is track mistake. only lead to a local optimul solution. Here is a counter example:

    1
    2
    3
    4
    5
    grid = [[1,1,1,0,1],
    [0,0,0,0,0],
    [0,0,0,0,0],
    [0,0,0,0,0],
    [1,0,1,1,1]].
  2. the right way is to setup two round trip DP, since the back trip will depand on the first one, we minimize the variables to 3, k, j p. No bull shit, let’s get started!
    We have to maintain two points for round trips.
    (i, j) and (p, q). This will have three constraits:

  3. i < p && j > q
  4. i == p && j == q
  5. i > p && j < q
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
public int cherryPickup(int[][] grid) {
int N = grid.length, M = (N << 1) - 1;
int[][] dp = new int[N][N];
dp[0][0] = grid[0][0];

for (int n = 1; n < M; n++) {
for (int i = N - 1; i >= 0; i--) {
for (int p = N - 1; p >= 0; p--) {
int j = n - i, q = n - p;

if (j < 0 || j >= N || q < 0 || q >= N || grid[i][j] < 0 || grid[p][q] < 0) {
dp[i][p] = -1;
continue;
}

if (i > 0) dp[i][p] = Math.max(dp[i][p], dp[i - 1][p]);
if (p > 0) dp[i][p] = Math.max(dp[i][p], dp[i][p - 1]);
if (i > 0 && p > 0) dp[i][p] = Math.max(dp[i][p], dp[i - 1][p - 1]);

if (dp[i][p] >= 0) dp[i][p] += grid[i][j] + (i != p ? grid[p][q] : 0)
}
}
}

return Math.max(dp[N - 1][N - 1], 0);
}