c++code:
class Solution {
public:
int cherryPickup(vector<vector<int>>& grid) {
int n = grid.size();
int maxK = 2 * n - 1;
int dp[maxK][n][n] = {-1};
memset(dp, -1, sizeof(dp));
for(int k = 0; k < maxK; k++) {
for(int xa = 0; xa < n && xa <= k; xa++) {
for(int xb = xa; xb < n && xb <= k; xb++) {
if(grid[xa][k - xa] == -1 || grid[xb][k - xb] == -1) continue;
int tmp = 0;
if(k > 0) {
tmp = dp[k - 1][xa][xb];
if(xb > 0) tmp = max(tmp, dp[k - 1][xa][xb - 1]);
if(xa > 0) tmp = max(tmp, dp[k - 1][xa - 1][xb]);
if(xa > 0 && xb > 0) tmp = max(tmp, dp[k - 1][xa - 1][xb - 1]);
}
if(tmp < 0) continue;
tmp += (xa == xb) ? grid[xa][k - xa] : grid[xa][k - xa] + grid[xb][k - xb];
dp[k][xa][xb] = tmp;
//cout<<k<<" "<<xa<<" "<<xb<<" "<<dp[k][xa][xb]<<endl;
}
}
}
return dp[maxK - 1][n - 1][n - 1] > 0 ? dp[maxK - 1][n - 1][n - 1] : 0;
}
};