DEV Community

Prashant Mishra
Prashant Mishra

Posted on

Cherry Pickup

Cherry pickup

class Solution {
    public int cherryPickup(int[][] grid) {
        // was able to understand from the post: https://leetcode.com/problems/cherry-pickup/solutions/329945/very-easy-to-follow-step-by-step-recursi-sjpg/
        //instead of moving from 0,0 and m-1,n-1 at the same time have two people moving from the 0,0 position and at any given point of time if both are at the same cell count onlly once.
        int n = grid.length;
        int dp[][][][] = new int[n][n][n][n];
        for(int dp3[][][] : dp){
            for(int dp2[][]: dp3){
                for(int dp1[] : dp2) Arrays.fill(dp1,-1);
            }
        }
        return Math.max(0,max(0,0,0,0,grid.length,grid,dp));
    }
    public int max(int i, int j, int k, int l, int n, int [][] grid, int[][][][]dp){
        //base case
        if(i>=n || j>=n || k>=n || l>=n || grid[i][j] ==-1 || grid[k][l]==-1) return Integer.MIN_VALUE;
         if(i ==n-1 && j ==n-1){
            return grid[i][j];// if any one reached the end return the value at the location
        }
        if(k ==n-1 && l ==n-1){
            return grid[k][l];// if any one reached the end return the value at the location
        }
        if(dp[i][j][k][l]!=-1) return dp[i][j][k][l];
        int cherries = 0;
        if(i==k && j == l){
            cherries+=grid[i][j];//count only once;
        }
        else{
            cherries+=grid[i][j] + grid[k][l];
        }
        cherries+= Math.max(max(i+1,j,k+1,l,n,grid,dp),
        Math.max(max(i+1,j,k,l+1,n,grid,dp),
        Math.max(max(i,j+1,k+1,l,n,grid,dp), 
        max(i,j+1,k,l+1,n,grid,dp))));

        return dp[i][j][k][l] = cherries;

    }
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)