GeeksforGeeks App
Open App
Browser
Continue

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

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

Naive Approach:

The recursive naive algorithm to maximize the cost of moving to the bottom-most row from top-left and top-right corner of the matrix is:

1. Define a recursive function “dp” that takes four arguments:
a. row: the current row in the matrix
b. col1: the current column of the first point
c. col2: the current column of the second point
d. grid: the matrix containing the costs at each cell
2. If either of the points move out of the grid, return 0.
3. Add the cost of the current cell to the result, and if the two points are not in the same cell, add the cost of the second cell to the result.
4. If the current row is not the bottom-most row:
a. Initialize the maximum variable to 0
b. For each possible movement of the two points, call the “dp” function recursively with the new positions of the points
c. Update the maximum variable with the maximum result obtained from all the recursive calls
d. Add the maximum variable to the result
5. Return the final result obtained from the “dp” function.

## C++

 `// C++ code to implement the approach``#include ``using` `namespace` `std;` `// Dp function``int` `dp(``int` `row, ``int` `col1, ``int` `col2, vector >& grid){``    ``if` `(col1 < 0 || col1 >= grid[0].size()``        ``|| col2 < 0 || col2 >= grid[0].size())``        ``return` `0;` `    ``// Add cost of the current cell``    ``int` `result = grid[row][col1];``    ``if` `(col1 != col2)``        ``result``            ``+= grid[row][col2];``    ` `      ``// analysing all possible movements of the two points``    ``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));` `        ``result += maximum;``    ``}` `    ``return` `result;``}` `// Function to maximize the cost``int` `pickup(vector >& grid)``{``    ``int` `M = grid.size();``    ``if` `(M == 0)``        ``return` `0;` `    ``int` `N = grid[0].size();``    ``if` `(N == 0)``        ``return` `0;` `    ``return` `dp(0, 0, N - 1, grid);``}` `// Driver code``int` `main()``{``    ``vector > grid{``        ``{ 3, 1, 1 }, { 2, 5, 1 },``        ``{ 1, 5, 5 }, { 2, 1, 1 }``    ``};``  ` `    ``cout << pickup(grid);``    ``return` `0;``}`

## Python3

 `# Python program to count the number of leading zeroes` `import` `sys` `# Dp function``def` `dp(row, col1, col2, grid):``    ``if` `col1 < ``0` `or` `col1 >``=` `len``(grid[``0``]) \``            ``or` `col2 < ``0` `or` `col2 >``=` `len``(grid[``0``]):``        ``return` `0` `    ``# Add cost of the current cell``    ``result ``=` `grid[row][col1]``    ``if` `col1 !``=` `col2:``        ``result ``+``=` `grid[row][col2]` `    ``# analysing all possible movements of the two points``    ``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))``        ``result ``+``=` `maximum` `    ``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` `    ``return` `dp(``0``, ``0``, N ``-` `1``, grid)` `# 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 rishabmilhdijo`

## Java

 `import` `java.util.*;` `public` `class` `Main {``    ``// Dp function``    ``public` `static` `int` `dp(``int` `row, ``int` `col1, ``int` `col2, ``int``[][] grid) {``        ``if` `(col1 < ``0` `|| col1 >= grid[``0``].length || col2 < ``0` `|| col2 >= grid[``0``].length) {``            ``return` `0``;``        ``}` `        ``// Add cost of the current cell``        ``int` `result = grid[row][col1];``        ``if` `(col1 != col2) {``            ``result += grid[row][col2];``        ``}` `        ``// analysing all possible movements of the two points``        ``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, grid));``                ``}``            ``}``            ``result += maximum;``        ``}` `        ``return` `result;``    ``}` `    ``// Function to maximize the cost``    ``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``;``        ``}` `        ``return` `dp(``0``, ``0``, N - ``1``, grid);``    ``}` `    ``// Driver code``    ``public` `static` `void` `main(String[] args) {``        ``int``[][] grid = {``            ``{``3``, ``1``, ``1``},``            ``{``2``, ``5``, ``1``},``            ``{``1``, ``5``, ``5``},``            ``{``2``, ``1``, ``1``}``        ``};` `        ``System.out.println(pickup(grid));``    ``}``}`

## C#

 `using` `System;` `public` `class` `GFG {``    ``static` `int` `DP(``int` `row, ``int` `col1, ``int` `col2, ``int``[][] grid){``        ``if` `(col1 < 0 || col1 >= grid[0].Length``            ``|| col2 < 0 || col2 >= grid[0].Length)``            ``return` `0;` `        ``int` `result = grid[row][col1];``        ``if` `(col1 != col2)``            ``result += grid[row][col2];` `        ``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, grid));` `            ``result += maximum;``        ``}` `        ``return` `result;``    ``}` `    ``static` `int` `Pickup(``int``[][] grid)``    ``{``        ``int` `M = grid.Length;``        ``if` `(M == 0)``            ``return` `0;` `        ``int` `N = grid[0].Length;``        ``if` `(N == 0)``            ``return` `0;` `        ``return` `DP(0, 0, N - 1, grid);``    ``}` `    ``public` `static` `void` `Main()``    ``{``        ``int``[][] grid = ``new` `int``[][] {``            ``new` `int``[] { 3, 1, 1 },``            ``new` `int``[] { 2, 5, 1 },``            ``new` `int``[] { 1, 5, 5 },``            ``new` `int``[] { 2, 1, 1 }``        ``};` `        ``Console.WriteLine(Pickup(grid));``    ``}``}`

## Javascript

 `// JavaScript code to implement the approach` `// Dp function``function` `dp(row, col1, col2, grid) {``    ``if` `(col1 < 0 || col1 >= grid[0].length || col2 < 0``        ``|| col2 >= grid[0].length)``        ``return` `0;` `    ``// Add cost of the current cell``    ``let result = grid[row][col1];``    ``if` `(col1 !== col2)``        ``result += grid[row][col2];` `    ``// analysing all possible movements of the two points``    ``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));` `        ``result += maximum;``    ``}` `    ``return` `result;``}` `// Function to maximize the cost``function` `pickup(grid) {``    ``const M = grid.length;``    ``if` `(M === 0)``        ``return` `0;` `    ``const N = grid[0].length;``    ``if` `(N === 0)``        ``return` `0;` `    ``return` `dp(0, 0, N - 1, grid);``}` `// Driver code``const grid = [``    ``[ 3, 1, 1 ],``    ``[ 2, 5, 1 ],``    ``[ 1, 5, 5 ],``    ``[ 2, 1, 1 ],``];` `// Function call``console.log(pickup(grid));`

Output

`24`

Time Complexity: 3N where N is number of rows.

Auxiliary Space: O(N) , where N is number of rows.

Efficient Approach:

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:
• 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 ``using` `namespace` `std;` `// Dp function``int` `dp(``int` `row, ``int` `col1, ``int` `col2,``       ``vector >& grid,``       ``vector > >& 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 >& grid)``{``    ``int` `M = grid.size();``    ``if` `(M == 0)``        ``return` `0;` `    ``int` `N = grid[0].size();``    ``if` `(N == 0)``        ``return` `0;` `    ``vector > >``    ``dpCache(M, vector >(``                   ``N, vector<``int``>(N, -1)));``    ``return` `dp(0, 0, N - 1, grid, dpCache);``}` `// Driver code``int` `main()``{``    ``vector > 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

 ``

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 ``using` `namespace` `std;` `// Function to maximize the cost``int` `pickup(vector >& grid)``{``    ``int` `M = grid.size();``    ``if` `(M == 0)``        ``return` `0;` `    ``int` `N = grid[0].size();``    ``if` `(N == 0)``        ``return` `0;` `    ``vector > > dp(``        ``M, vector >(``               ``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 > 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> grid)``  ``{``    ``int` `M = grid.size();``    ``if` `(M == ``0``){``      ``return` `0``;``    ``}` `    ``int` `N = grid.get(``0``).size();``    ``if` `(N == ``0``){``      ``return` `0``;``    ``}` `    ``ArrayList>> dp = ``new` `ArrayList>>();` `    ``// Initializing dp arraylist``    ``for``(``int` `i = ``0` `; i < M ; i++){``      ``ArrayList> temp = ``new` `ArrayList>();``      ``for``(``int` `j = ``0` `; j < N ; j++){``        ``ArrayList temp1 = ``new` `ArrayList();``        ``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> grid = ``new` `ArrayList>(``      ``List.of(``        ``new` `ArrayList(``          ``List.of(``3``, ``1``, ``1``)``        ``),``        ``new` `ArrayList(``          ``List.of(``2``, ``5``, ``1``)``        ``),``        ``new` `ArrayList(``          ``List.of(``1``, ``5``, ``5``)``        ``),``        ``new` `ArrayList(``          ``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

 ``

Output

`-2147483648 -2147483648 4 -2147483648 -2147483648 -2147483648 -2147483648 -2147483648 -2147483648 -2147483646 11 7 -2147483641 9 10 -2147483645 -2147483642 -2147483647 12 17 17 17 16 21 15 20 15 19 24 24 23 22 23 23 23 22 24`

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

Implementation 2: With State Compression

## C++

 `// C++ code to implement the approach``#include ``using` `namespace` `std;` `// Function to maximize the cost``int` `pickup(vector >& grid)``{``    ``int` `M = grid.size();``    ``if` `(M == 0)``        ``return` `0;` `    ``int` `N = grid[0].size();``    ``if` `(N == 0)``        ``return` `0;` `    ``vector > > dp(``        ``2, vector >(``               ``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 > 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``                  ``|| 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`

## C#

 `using` `System;``using` `System.Collections.Generic;` `namespace` `Pickup``{``  ``class` `Program``  ``{``    ``static` `void` `Main(``string``[] args)``    ``{``      ``int``[][] grid = ``new` `int``[][] {``        ``new` `int``[] { 3, 1, 1 }, ``new` `int``[] { 2, 5, 1 },``        ``new` `int``[] { 1, 5, 5 }, ``new` `int``[] { 2, 1, 1 }``      ``};` `      ``Console.WriteLine(MaximizeCost(grid));``    ``}` `    ``// Function to maximize the cost``    ``static` `int` `MaximizeCost(``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][][];``      ``for` `(``int` `i = 0; i < 2; i++)``      ``{``        ``dp[i] = ``new` `int``[N][];``        ``for` `(``int` `j = 0; j < N; j++)``        ``{``          ``dp[i][j] = ``new` `int``[N];``          ``for` `(``int` `k = 0; k < N; k++)``          ``{``            ``dp[i][j][k] = ``int``.MinValue;``          ``}``        ``}``      ``}` `      ``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;``    ``}``  ``}``}` `// This code is contributed by unstoppablepandu.`

## Javascript

 ``

Output

`24`

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

My Personal Notes arrow_drop_up