Chocolate Pickup

Chocolate Pickup

Chocolate Pickup - 3D DP

https://www.codingninjas.com/studio/problems/chocolate-pickup_3125885?utm_source=striver&utm_medium=website&utm_campaign=a_zcoursetuf

My approach:

In this question, there are two fixed starting and variable ending points, but as per the movement of Alice and Bob, we know that they will end in the last row. They have to move together at a time to the next row.

image1

Code:

int helper(int r, int c, vector<vector<int>>& grid, int i, int j1, int j2, vector<vector<vector<int>>>& dp){
    if(j1<0 || j1>=c || j2<0 || j2>=c){
        return -1e8;
    }

    if(i==r-1){
        if(j1==j2){
            return grid[i][j1];
        }else{
            return grid[i][j1]+grid[i][j2];
        }
    }

    if(dp[i][j1][j2]!=-1){
        return dp[i][j1][j2];
    }

    int maxi = -1e8;
    for(int k1=-1; k1<=1; k1++){
        for(int k2=-1; k2<=1; k2++){
            if(j1==j2){
                maxi = max(maxi, grid[i][j1] + helper(r,c,grid,i+1,j1+k1,j2+k2,dp));
            }else{
                maxi = max(maxi, grid[i][j1] + grid[i][j2] + helper(r,c,grid,i+1,j1+k1,j2+k2,dp));
            }
        }
    }

    dp[i][j1][j2] = maxi;
    return maxi;
}

int maximumChocolates(int r, int c, vector<vector<int>> &grid) {
    // Write your code here.
    vector<vector<vector<int>>> dp(r, vector<vector<int>>(c, vector<int>(c,-1)));
    return helper(r,c,grid,0,0,c-1,dp);
}