Skip to content
Related Articles

Related Articles

Maximize cost to reach the bottom-most row from top-left and top-right corner of given matrix

View Discussion
Improve Article
Save Article
  • Last Updated : 28 Jun, 2022
View Discussion
Improve Article
Save Article

Given a matrix grid[][] of size M * N where each cell of the matrix denotes the cost to be present on that cell. The task is to maximize the cost of moving to the bottom-most row from top-left and top-right corner of the matrix where in each step:

  • From the cell (i, j) there can be a movement to (i+1, j-1), (i+1, j) or (i+1, j+1).
  • If both the points are in the same cell at the same time, the cost of the cell will be added for only one.
  • At no instance of time, the points can move out of the grid.

Examples:

Input: 
grid = {{3, 1, 1}, 
            {2, 5, 1}, 
            {1, 5, 5}, 
            {2, 1, 1}}
Output: 24
Explanation: Path from top-left and top-right are described in color orange and blue respectively.
Cost for first path is (3 + 2 + 5 + 2) = 12.
Cost for second path is (1 + 5 + 5 + 1) = 12.
Total cost is 12 + 12 = 24.

Ex1 – Visual Grid

Input:
grid = {{1, 0, 0, 0, 0, 0, 1}, 
            {2, 0, 0, 0, 0, 3, 0}, 
            {2, 0, 9, 0, 0, 0, 0}, 
            {0, 3, 0, 5, 4, 0, 0}, 
            {1, 0, 2, 3, 0, 0, 6}}
Output: 28
Explanation: Path from top-left and top-right are described in color orange and blue respectively.
Cost of the first path is (1 + 9 + 5 + 2) = 17.
Cost of the second path is (1 + 3 + 4 + 3) = 11.
Total cost of the paths is 17 + 11 = 28.
This is the maximum cost possible.

Ex2 – Visual Grid

 

Intuition: Denote the point at the top-left corner as point1 and at the top-right corner as point2. Following is the intuition behind the solution of the problem.

  • Note that the order of their movements does not matter since it would not impact the final result. The final cost depends on the tracks of the points. Therefore, movements can be in any order. There is a need to apply DP, so look for an order that is suitable for DP. Try here a few possible moving orders. 
     

Can point1 be moved firstly to the bottom row, and then point2?

Maybe not. In this case, the movement of point1 will impact the movement of point2. In other words, the optimal track of point2 depends on the track of point1. In this case there will be requirement to record the whole track of point1 as the state for point2 in DP. The number of sub-problems is too much.

In fact, in any case, when anyone point is moved several steps earlier than the other, the movement of the first point will impact the movement of the other point. So both the points should be moved synchronously.

  • Define the DP state as (row1, col1, row2, col2), where (row1, col1) represents the location of point1, and (row2, col2) represents the location of point2. If they are moved synchronously, both the points will always be on the same row. Therefore, row1 = row2
    Let row = row1 = row2. The DP state is simplified to (row, col1, col2), where (row, col1) represents the location of point1, and (row, col2) represents the location of point2.
  • So for the DP function: Let dp(row, col1, col2) return the maximum cost, if point1 starts at (row, col1) and point2 starts at (row, col2).
  • The base cases are that both the points start at the bottom line. In this case, no need to move, just the cost at current cells are considered. Remember not to double count if the points are at exactly the same cell.
  • In other cases, add the maximum cost of the paths in the future. Here comes the transition function. Since points can move synchronously, and each point has three different movements for one step, there totally are 3*3 = 9 possible movements for two robots:
Sl. No.Point1 movementPoint2 movement
1Left DownLeft Down
2Left DownDown
3Left DownRight Down
4DownLeft Down
5DownDown
6DownRight Down
7Right DownLeft Down
8Right DownDown
9Right DownRight Down
  • The maximum cost of paths in the future would be the max of those 9 movements, which is the maximum of 
    dp(row+1, new_col1, new_col2), where new_col1 can be col1, col1+1, or col1-1, and new_col2 can be col2, col2+1, or col2-1.

Approach 1 – Dynamic Programming (Bottom Up): The problem solution is based on dynamic programming concept and uses the above intuition.

  • Define a dp function that takes three integers row, col1, and col2 as input.
    • (row, col1) represents the location of point1, and (row, col2) represents the location of point2.
    • The dp function returns the maximum cost if point1 starts at (row, col1) and point2 starts at (row, col2).
  • In the dp function:
    • Add the cost at (row, col1) and (row, col2). Do not double count if col1 = col2.
    • If the last row is not reached, add the maximum cost that can be obtained in the future path.
    • The maximum cost that can be achieved in the future is the maximum of dp(row+1, new_col1, new_col2), where new_col1 can be col1, col1+1, or col1-1, and new_col2 can be col2, col2+1, or col2-1.
    • Return the total cost.
  • Finally, return dp(row=0, col1=0, col2=last_column) in the main function.

Below is the implementation of the above approach.

C++




// C++ code to implement the approach
#include <bits/stdc++.h>
using namespace std;
 
// Dp function
int dp(int row, int col1, int col2,
       vector<vector<int> >& grid,
       vector<vector<vector<int> > >& dpCache)
{
    if (col1 < 0 || col1 >= grid[0].size()
        || col2 < 0 || col2 >= grid[0].size())
        return 0;
 
    // Check cache
    if (dpCache[row][col1][col2] != -1)
        return dpCache[row][col1][col2];
 
    // Add cost of the current cell
    int result = grid[row][col1];
    if (col1 != col2)
        result
            += grid[row][col2];
 
    // DP transition
    if (row != grid.size() - 1) {
        int maximum = 0;
        for (int newCol1 = col1 - 1;
             newCol1 <= col1 + 1; newCol1++)
            for (int newCol2 = col2 - 1;
                 newCol2 <= col2 + 1;
                 newCol2++)
                maximum
                    = max(maximum,
                          dp(row + 1, newCol1,
                             newCol2, grid,
                             dpCache));
 
        result += maximum;
    }
 
    dpCache[row][col1][col2] = result;
    return result;
}
 
// Function to maximize the cost
int pickup(vector<vector<int> >& grid)
{
    int M = grid.size();
    if (M == 0)
        return 0;
 
    int N = grid[0].size();
    if (N == 0)
        return 0;
 
    vector<vector<vector<int> > >
    dpCache(M, vector<vector<int> >(
                   N, vector<int>(N, -1)));
    return dp(0, 0, N - 1, grid, dpCache);
}
 
// Driver code
int main()
{
    vector<vector<int> > grid{
        { 3, 1, 1 }, { 2, 5, 1 },
        { 1, 5, 5 }, { 2, 1, 1 }
    };
    cout << pickup(grid);
    return 0;
}

Java




// Java code to implement the approach
import java.util.*;
 
class GFG{
  static int[][] grid = {
    { 3, 1, 1 }, { 2, 5, 1 },
    { 1, 5, 5 }, { 2, 1, 1 }
  };
  static int[][][] dpCache;
 
  // Dp function
  static int dp(int row, int col1, int col2)
  {
    if (col1 < 0 || col1 >= grid[0].length
        || col2 < 0 || col2 >= grid[0].length)
      return 0;
 
    // Check cache
    if (dpCache[row][col1][col2] != -1)
      return dpCache[row][col1][col2];
 
    // Add cost of the current cell
    int result = grid[row][col1];
    if (col1 != col2)
      result
      += grid[row][col2];
 
    // DP transition
    if (row != grid.length - 1) {
      int maximum = 0;
      for (int newCol1 = col1 - 1;
           newCol1 <= col1 + 1; newCol1++)
        for (int newCol2 = col2 - 1;
             newCol2 <= col2 + 1;
             newCol2++)
          maximum
          = Math.max(maximum,
                     dp(row + 1, newCol1,
                        newCol2));
 
      result += maximum;
    }
 
    dpCache[row][col1][col2] = result;
    return result;
  }
 
  // Function to maximize the cost
  static int pickup()
  {
    int M = grid.length;
    if (M == 0)
      return 0;
 
    int N = grid[0].length;
    if (N == 0)
      return 0;
 
 
 
    dpCache = new int[M][N][N];
    for(int i = 0; i < M; i++)
    {
      for(int j = 0; j < N; j++)
      {
        for(int l = 0; l < N; l++)
          dpCache[i][j][l] = -1;
      }
    }
    return dp(0, 0, N - 1);
  }
 
  // Driver code
  public static void main(String[] args)
  {
 
    System.out.print(pickup());
  }
}
 
// This code is contributed by Rajput-Ji

Python3




# python3 code to implement the approach
 
# Dp function
 
 
def dp(row, col1, col2, grid, dpCache):
 
    if (col1 < 0 or col1 >= len(grid[0])
            or col2 < 0 or col2 >= len(grid[0])):
        return 0
 
    # Check cache
    if (dpCache[row][col1][col2] != -1):
        return dpCache[row][col1][col2]
 
    # Add cost of the current cell
    result = grid[row][col1]
    if (col1 != col2):
        result += grid[row][col2]
 
    # DP transition
    if (row != len(grid) - 1):
        maximum = 0
        for newCol1 in range(col1-1, col1 + 2):
            for newCol2 in range(col2-1, col2+2):
                maximum = max(maximum,
                              dp(row + 1, newCol1,
                                 newCol2, grid,
                                 dpCache))
 
        result += maximum
 
    dpCache[row][col1][col2] = result
    return result
 
 
# Function to maximize the cost
def pickup(grid):
 
    M = len(grid)
    if (M == 0):
        return 0
 
    N = len(grid[0])
    if (N == 0):
        return 0
 
    dpCache = [[[-1 for _ in range(N)] for _ in range(N)] for _ in range(M)]
    return dp(0, 0, N - 1, grid, dpCache)
 
 
# Driver code
if __name__ == "__main__":
 
    grid = [
        [3, 1, 1], [2, 5, 1],
        [1, 5, 5], [2, 1, 1]
    ]
    print(pickup(grid))
 
# This code is contributed by rakeshsahni

C#




// C# code to implement the approach
using System;
 
public class GFG{
  static int[,] grid = {
    { 3, 1, 1 }, { 2, 5, 1 },
    { 1, 5, 5 }, { 2, 1, 1 }
  };
  static int[,,] dpCache;
 
  // Dp function
  static int dp(int row, int col1, int col2)
  {
    if (col1 < 0 || col1 >= grid.GetLength(1)
        || col2 < 0 || col2 >= grid.GetLength(1))
      return 0;
 
    // Check cache
    if (dpCache[row,col1,col2] != -1)
      return dpCache[row,col1,col2];
 
    // Add cost of the current cell
    int result = grid[row,col1];
    if (col1 != col2)
      result
      += grid[row,col2];
 
    // DP transition
    if (row != grid.GetLength(0) - 1) {
      int maximum = 0;
      for (int newCol1 = col1 - 1;
           newCol1 <= col1 + 1; newCol1++)
        for (int newCol2 = col2 - 1;
             newCol2 <= col2 + 1;
             newCol2++)
          maximum
          = Math.Max(maximum,
                     dp(row + 1, newCol1,
                        newCol2));
 
      result += maximum;
    }
 
    dpCache[row,col1,col2] = result;
    return result;
  }
 
  // Function to maximize the cost
  static int pickup()
  {
    int M = grid.GetLength(0);
    if (M == 0)
      return 0;
 
    int N = grid.GetLength(1);
    if (N == 0)
      return 0;
 
 
 
    dpCache = new int[M,N,N];
    for(int i = 0; i < M; i++)
    {
      for(int j = 0; j < N; j++)
      {
        for(int l = 0; l < N; l++)
          dpCache[i,j,l] = -1;
      }
    }
    return dp(0, 0, N - 1);
  }
 
  // Driver code
  public static void Main(String[] args)
  {
 
    Console.Write(pickup());
  }
}
 
// This code contributed by shikhasingrajput

Javascript




<script>
 
// JavaScript code to implement the approach
 
// Dp function
function dp(row, col1, col2, grid, dpCache)
{
    if (col1 < 0 || col1 >= grid[0].length
        || col2 < 0 || col2 >= grid[0].length)
        return 0;
 
    // Check cache
    if (dpCache[row][col1][col2] != -1)
        return dpCache[row][col1][col2];
 
    // Add cost of the current cell
    let result = grid[row][col1];
    if (col1 != col2)
        result
            += grid[row][col2];
 
    // DP transition
    if (row != grid.length - 1) {
        let maximum = 0;
        for (let newCol1 = col1 - 1;newCol1 <= col1 + 1; newCol1++){
            for (let newCol2 = col2 - 1;newCol2 <= col2 + 1;newCol2++){
                maximum = Math.max(maximum, dp(row + 1, newCol1, newCol2, grid, dpCache));
            }
        }
 
        result += maximum;
    }
 
    dpCache[row][col1][col2] = result;
    return result;
}
 
// Function to maximize the cost
function pickup(grid)
{
    let M = grid.length;
    if (M == 0)
        return 0;
 
    let N = grid[0].length;
    if (N == 0)
        return 0;
 
    let dpCache = new Array(M);
    for(let i = 0; i < M; i++)
    {
        dpCache[i] = new Array(N);
        for(let j = 0; j < N; j++)
        {
            dpCache[i][j] = new Array(N).fill(-1);
        }
    }
    return dp(0, 0, N - 1, grid, dpCache);
}
 
// Driver code
let grid = [[ 3, 1, 1 ], [ 2, 5, 1 ],
        [ 1, 5, 5 ], [ 2, 1, 1 ]
    ];
document.write(pickup(grid));
 
// This code is contributed by shinjanpatra
 
</script>

Output

24

Time Complexity: O(M * N2)
Auxiliary Space: O(M * N2)

Approach 2 – Dynamic Programming (Top Down): This solution is also based on the dynamic programming approach which uses the intuition mentioned above. The only difference is that here it uses the top-down approach.

  • Define a three-dimensional dp array where each dimension has a size of M, N, and N respectively, similar to approach 1.
  • Here dp[row][col1][col2] represents the maximum cost upon reaching point1 at (row, col1) and point2 at (row, col2) position.
  • To compute dp[row][col1][col2] (transition equation):
    • Add the cost at (row, col1) and (row, col2). Do not double count if col1 = col2.
    • If not in the first row, add the maximum cost of the path already visited.
  • Finally, return the maximum value from the last row.

Note: State compression can be used to save the first dimension: dp[col1][col2]. Just reuse the dp array after iterating one row.

Implementation 1: No State Compression

C++




// C++ code to implement the approach
#include <bits/stdc++.h>
using namespace std;
 
// Function to maximize the cost
int pickup(vector<vector<int> >& grid)
{
    int M = grid.size();
    if (M == 0)
        return 0;
 
    int N = grid[0].size();
    if (N == 0)
        return 0;
 
    vector<vector<vector<int> > > dp(
        M, vector<vector<int> >(
               N, vector<int>(N, INT_MIN)));
    dp[0][0][N - 1] = grid[0][0]
                      + grid[0][N - 1];
 
    for (int i = 1; i < M; i++)
        for (int a = 0; a < N; a++)
            for (int b = 0; b < N; b++)
                for (int l = a - 1; l
                                    <= a + 1;
                     l++)
                    for (int r = b - 1;
                         r <= b + 1; r++) {
                        if (l < 0 || l >= N
                            || r < 0
                            || r >= N)
                            continue;
 
                        dp[i][a][b] = max(
                            dp[i][a][b],
                            ((a != b)
                                 ? grid[i][a]
                                       + grid[i][b]
                                 : grid[i][a])
                                + dp[i - 1][l][r]);
                    }
     
  for (int i =0 ;i <M;i++)
    for(int j =0 ;j < N;j++)
      for (int k =0;k <N;k++)
        cout<<dp[i][j][k]<<" ";
   
    int ans = 0;
    for (int a = 0; a < N; a++)
        for (int b = 0; b < N; b++)
            ans = max(ans, dp[M - 1][a][b]);
 
    return ans;
}
 
// Driver code
int main()
{
    vector<vector<int> > grid{
        { 3, 1, 1 }, { 2, 5, 1 },
        { 1, 5, 5 }, { 2, 1, 1 }
    };
    cout << pickup(grid);
    return 0;
}

Java




import java.util.*;
import java.io.*;
 
// Java program for the above approach
class GFG{
 
  // Function to maximize the cost
  public static int pickup(ArrayList<ArrayList<Integer>> grid)
  {
    int M = grid.size();
    if (M == 0){
      return 0;
    }
 
    int N = grid.get(0).size();
    if (N == 0){
      return 0;
    }
 
    ArrayList<ArrayList<ArrayList<Integer>>> dp = new ArrayList<ArrayList<ArrayList<Integer>>>();
 
    // Initializing dp arraylist
    for(int i = 0 ; i < M ; i++){
      ArrayList<ArrayList<Integer>> temp = new ArrayList<ArrayList<Integer>>();
      for(int j = 0 ; j < N ; j++){
        ArrayList<Integer> temp1 = new ArrayList<Integer>();
        for(int k = 0 ; k < N ; k++){
          temp1.add(Integer.MIN_VALUE);
        }
        temp.add(temp1);
      }
      dp.add(temp);
    }
 
    dp.get(0).get(0).set(N - 1, grid.get(0).get(0) + grid.get(0).get(N - 1));
 
    for (int i = 1; i < M; i++){
      for (int a = 0; a < N; a++){
        for (int b = 0; b < N; b++){
          for (int l = a - 1; l <= a + 1; l++){
            for (int r = b - 1; r <= b + 1; r++) {
              if (l < 0 || l >= N || r < 0 || r >= N)
                continue;
              dp.get(i).get(a).set(b, Math.max(dp.get(i).get(a).get(b), ((a != b) ? grid.get(i).get(a) + grid.get(i).get(b) : grid.get(i).get(a)) + dp.get(i-1).get(l).get(r)));
            }
          }
        }
      }
    }
 
    int ans = 0;
    for (int a = 0 ; a < N ; a++){
      for (int b = 0 ; b < N ; b++){
        ans = Math.max(ans, dp.get(M - 1).get(a).get(b));
      }
    }
 
    return ans;
  }
 
 
  // Driver code
  public static void main(String args[])
  {
    ArrayList<ArrayList<Integer>> grid = new ArrayList<ArrayList<Integer>>(
      List.of(
        new ArrayList<Integer>(
          List.of(3, 1, 1)
        ),
        new ArrayList<Integer>(
          List.of(2, 5, 1)
        ),
        new ArrayList<Integer>(
          List.of(1, 5, 5)
        ),
        new ArrayList<Integer>(
          List.of(2, 1, 1)
        )
      )
    );
    System.out.println(pickup(grid));
  }
}
 
// This code is contributed by subhamgoyal2014.

Python3




# Python code to implement the approach
 
# Function to maximize the cost
import sys
 
def pickup(grid):
 
    M = len(grid)
    if (M == 0):
        return 0
 
    N = len(grid[0])
    if (N == 0):
        return 0
 
    dp = [[[(-sys.maxsize-1) for i in range(N)] for j in range(N)] for k in range(M)]
    dp[0][0][N - 1] = grid[0][0] + grid[0][N - 1]
 
    for i in range(1,M):
        for a in range(N):
            for b in range(N):
                for l in range(a - 1,a + 2):
                    for r in range(b - 1,b + 2):
                        if (l < 0 or l >= N or r < 0 or r >= N):
                            continue
 
                        dp[i][a][b] = max(dp[i][a][b],(grid[i][a]+ grid[i][b] if (a != b) else grid[i][a]) + dp[i - 1][l][r])
   
    ans = 0
    for a in range(N):
        for b in range(N):
            ans = max(ans, dp[M - 1][a][b])
    return ans
 
# Driver code
grid = [[ 3, 1, 1 ], [ 2, 5, 1 ],
        [ 1, 5, 5 ], [ 2, 1, 1 ]]
 
print(pickup(grid))
 
# This code is contributed by shinjanpatra

C#




// C# code to implement the approach
using System;
class GFG
{
   
  // Function to maximize the cost
  static int pickup(int[,] grid)
  {
    int M = grid.GetLength(0);
    if (M == 0)
      return 0;
 
    int N = grid.GetLength(1);
    if (N == 0)
      return 0;
 
    int [,,]dp = new int[M,N,N];
    dp[0,0,N - 1] = grid[0,0]
      + grid[0,N - 1];
 
    for (int i = 1; i < M; i++)
      for (int a = 0; a < N; a++)
        for (int b = 0; b < N; b++)
          for (int l = a - 1; l
               <= a + 1;
               l++)
            for (int r = b - 1;
                 r <= b + 1; r++) {
              if (l < 0 || l >= N
                  || r < 0
                  || r >= N)
                continue;
 
              dp[i,a,b] = Math.Max(
                dp[i,a,b],
                ((a != b)
                 ? grid[i,a]
                 + grid[i,b]
                 : grid[i,a])
                + dp[i - 1,l,r]);
            }
 
    int ans = 0;
    for (int a = 0; a < N; a++)
      for (int b = 0; b < N; b++)
        ans = Math.Max(ans, dp[M - 1,a,b]);
 
    return ans;
  }
 
  // Driver code
  public static void Main()
  {
    int[,] grid = {
      { 3, 1, 1 }, { 2, 5, 1 },
      { 1, 5, 5 }, { 2, 1, 1 }
    };
    Console.WriteLine( pickup(grid));
 
  }}
 
// This code is contributed by ukasp.

Javascript




<script>
        // JavaScript code for the above approach
 
 
        // Function to maximize the cost
        function pickup(grid) {
            let M = grid.length;
            if (M == 0)
                return 0;
 
            let N = grid[0].length;
            if (N == 0)
                return 0;
 
 
            let dp = new Array(M);
            for (let i = 0; i < dp.length; i++) {
                dp[i] = new Array(N);
                for (let j = 0; j < dp[i].length; j++) {
                    dp[i][j] = new Array(N).fill(Number.MIN_VALUE)
                }
            }
            dp[0][0][N - 1] = grid[0][0]
                + grid[0][N - 1];
 
            for (let i = 1; i < M; i++)
                for (let a = 0; a < N; a++)
                    for (let b = 0; b < N; b++)
                        for (let l = a - 1; l
                            <= a + 1;
                            l++)
                            for (let r = b - 1;
                                r <= b + 1; r++) {
                                if (l < 0 || l >= N
                                    || r < 0
                                    || r >= N)
                                    continue;
 
                                dp[i][a][b] = Math.max(
                                    dp[i][a][b],
                                    ((a != b)
                                        ? grid[i][a]
                                        + grid[i][b]
                                        : grid[i][a])
                                    + dp[i - 1][l][r]);
                            }
 
            let ans = 0;
            for (let a = 0; a < N; a++)
                for (let b = 0; b < N; b++)
                    ans = Math.max(ans, dp[M - 1][a][b]);
 
            return ans;
        }
 
        // Driver code
 
        let grid = [
            [3, 1, 1], [2, 5, 1],
            [1, 5, 5], [2, 1, 1]
        ];
        document.write(pickup(grid));
 
 
       // This code is contributed by Potta Lokesh
    </script>

Output

24

Time Complexity: O(M * N2)
Auxiliary Space: O(M * N2)

Implementation 2: With State Compression

C++




// C++ code to implement the approach
#include <bits/stdc++.h>
using namespace std;
 
// Function to maximize the cost
int pickup(vector<vector<int> >& grid)
{
    int M = grid.size();
    if (M == 0)
        return 0;
 
    int N = grid[0].size();
    if (N == 0)
        return 0;
 
    vector<vector<vector<int> > > dp(
        2, vector<vector<int> >(
               N, vector<int>(N, INT_MIN)));
    dp[0][0][N - 1] = grid[0][0]
                      + grid[0][N - 1];
 
    // Looping over all rows
    for (int i = 1; i < M; i++)
 
        // looping over every cell
        // in the row for point1
        for (int a = 0; a < N; a++)
 
            // looping over every cell
            // in the row for point2
            for (int b = 0; b < N; b++)
 
                // Capturing possible
                // movements of point 1
                for (int l = a - 1;
                     l <= a + 1; l++)
 
                    // Capturing possible
                    // movements of point2
                    for (int r = b - 1;
                         r <= b + 1; r++) {
                        if (l < 0 || l >= N
                            || r < 0 || r >= N)
                            continue;
 
                        // Apply DP transition
                        dp[i % 2][a][b] = max(
                            dp[i % 2][a][b],
                            ((a != b)
                                 ? grid[i][a]
                                       + grid[i][b]
                                 : grid[i][a])
                                + dp[(i - 1) % 2][l][r]);
                    }
 
    // Loop over dp to get the final answer
    int ans = 0;
    for (int a = 0; a < N; a++)
        for (int b = 0; b < N; b++)
            ans = max(ans,
                      dp[(M - 1) % 2][a][b]);
 
    return ans;
}
 
// Driver code
int main()
{
    vector<vector<int> > grid{
        { 3, 1, 1 }, { 2, 5, 1 },
        { 1, 5, 5 }, { 2, 1, 1 }
    };
    cout << pickup(grid);
    return 0;
}

Java




// Online Java Compiler
// Use this editor to write, compile and run your Java code online
class GFG {
  public static int pickup(int[][] grid){
    int M = grid.length;
    if (M == 0)
      return 0;
 
    int N = grid[0].length;
    if (N == 0)
      return 0;
 
    int dp[][][] = new int[2][N][N];
    for(int i=0;i<2;i++){
 
      for(int j=0;j<N;j++){
        for(int k=0;k<N;k++){
          dp[i][j][k] = Integer.MIN_VALUE;
        }
      }
    }
 
    dp[0][0][N - 1] = grid[0][0]
      + grid[0][N - 1];
 
    // Looping over all rows
    for (int i = 1; i < M; i++)
 
      // looping over every cell
      // in the row for point1
      for (int a = 0; a < N; a++)
 
        // looping over every cell
        // in the row for point2
        for (int b = 0; b < N; b++)
 
          // Capturing possible
          // movements of point 1
          for (int l = a - 1;
               l <= a + 1; l++)
 
            // Capturing possible
            // movements of point2
            for (int r = b - 1;
                 r <= b + 1; r++) {
              if (l < 0 || l >= N
                  || r < 0 || r >= N)
                continue;
 
              // Apply DP transition
              dp[i % 2][a][b] = Math.max(
                dp[i % 2][a][b],
                ((a != b)
                 ? grid[i][a]
                 + grid[i][b]
                 : grid[i][a])
                + dp[(i - 1) % 2][l][r]);
            }
 
    // Loop over dp to get the final answer
    int ans = 0;
    for (int a = 0; a < N; a++)
      for (int b = 0; b < N; b++)
        ans = Math.max(ans,
                       dp[(M - 1) % 2][a][b]);
 
    return ans;
  }
  public static void main(String[] args) {
    int [][]grid = new int[][]{{ 3, 1, 1 }, { 2, 5, 1 },
                             { 1, 5, 5 }, { 2, 1, 1 }};
    System.out.println(pickup(grid));
 
  }
}
 
// This code is contributed by akshitsexanaa09.

Python3




# Python code to implement the approach
 
# Function to Math.maximize the cost
import sys
 
def pickup(grid):
 
    M = len(grid)
    if (M == 0):
        return 0
 
    N = len(grid[0])
    if (N == 0):
        return 0
 
    dp = [[[-sys.maxsize -1 for i in range(N)]for j in range(N)]for k in range(2)]
      
    dp[0][0][N - 1] = grid[0][0] + grid[0][N - 1]
 
    # Looping over all rows
    for i in range(1,M):
 
        # looping over every cell
        # in the row for point1
        for a in range(N):
 
            # looping over every cell
            # in the row for point2
            for b in range(N):
 
                # Capturing possible
                # movements of point1
                for l in range(a - 1,a + 2):
 
                    # Capturing possible
                    # movements of point2
                    for r in range(b - 1,b + 2):
                        if (l < 0 or l >= N or r < 0 or r >= N):
                            continue
 
                        # Apply DP transition
                        dp[i % 2][a][b] = max(dp[i % 2][a][b],(grid[i][a]+ grid[i][b] if (a != b) else grid[i][a]) + dp[(i - 1) % 2][l][r])
                     
 
    # Loop over dp to get the final answer
    ans = 0
    for a in range(N):
        for b in range(N):
            ans = max(ans,dp[(M - 1) % 2][a][b])
 
    return ans
 
# Driver code
grid = [ [ 3, 1, 1 ], [ 2, 5, 1 ],
             [ 1, 5, 5 ], [ 2, 1, 1 ] ]
 
print(pickup(grid))
 
# This code is contributed by shinjanpatra

Javascript




<script>
 
// JavaScript code to implement the approach
 
// Function to Math.maximize the cost
function pickup(grid)
{
    let M = grid.length;
    if (M == 0)
        return 0;
 
    let N = grid[0].length;
    if (N == 0)
        return 0;
 
    let dp = new Array(2);
    for(let i=0;i<2;i++){
        dp[i] = new Array(N);
        for(let j=0;j<N;j++){
            dp[i][j] = new Array(N).fill(Number.MIN_VALUE);
        }
    }
      
    dp[0][0][N - 1] = grid[0][0]
                      + grid[0][N - 1];
 
    // Looping over all rows
    for (let i = 1; i < M; i++)
 
        // looping over every cell
        // in the row for point1
        for (let a = 0; a < N; a++)
 
            // looping over every cell
            // in the row for point2
            for (let b = 0; b < N; b++)
 
                // Capturing possible
                // movements of point 1
                for (let l = a - 1;
                     l <= a + 1; l++)
 
                    // Capturing possible
                    // movements of point2
                    for (let r = b - 1;
                         r <= b + 1; r++) {
                        if (l < 0 || l >= N
                            || r < 0 || r >= N)
                            continue;
 
                        // Apply DP transition
                        dp[i % 2][a][b] = Math.max(
                            dp[i % 2][a][b],
                            ((a != b)
                                 ? grid[i][a]
                                       + grid[i][b]
                                 : grid[i][a])
                                + dp[(i - 1) % 2][l][r]);
                    }
 
    // Loop over dp to get the final answer
    let ans = 0;
    for (let a = 0; a < N; a++)
        for (let b = 0; b < N; b++)
            ans = Math.max(ans,
                      dp[(M - 1) % 2][a][b]);
 
    return ans
}
 
// Driver code
 
let grid = [ [ 3, 1, 1 ], [ 2, 5, 1 ],
             [ 1, 5, 5 ], [ 2, 1, 1 ] ]
 
document.write(pickup(grid))
 
// This code is contributed by shinjanpatra
 
</script>

Output

24

Time Complexity: O(M * N2)
Auxiliary Space: O(N2)


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!