Given a gold mine of n*m dimensions. Each field in this mine contains a positive integer which is the amount of gold in tons. Initially, the miner is in the first column but can be in any row. He can move only (right->,right up /,right down\) that is from a given cell, the miner can move to the cell diagonally up towards the right or diagonally down towards the right. Find out the maximum amount of gold he can collect.Â
Examples:Â
Input : mat[][] = {{1, 3, 3},
{2, 1, 4},
{0, 6, 4}};
Output : 12
{(1,0)->(2,1)->(1,2)}
Input: mat[][] = { {1, 3, 1, 5},
{2, 2, 4, 1},
{5, 0, 2, 3},
{0, 6, 1, 2}};
Output : 16
(2,0) -> (1,1) -> (1,2) -> (0,3) OR
(2,0) -> (3,1) -> (2,2) -> (2,3)
Input : mat[][] = {{10, 33, 13, 15},
{22, 21, 04, 1},
{5, 0, 2, 3},
{0, 6, 14, 2}};
Output : 83
Source Flipkart InterviewÂ
Method 1: Recursion
A simple method that is a direct recursive implementationÂ
C++
// C++ program to solve Gold Mine problem#include<bits/stdc++.h>using namespace std;Â
int collectGold(vector<vector<int>> gold, int x, int y, int n, int m) {Â
    // Base condition.    if ((x < 0) || (x == n) || (y == m)) {         return 0;    }   Â
    // Right upper diagonal    int rightUpperDiagonal = collectGold(gold, x - 1, y + 1, n, m); Â
     // right    int right = collectGold(gold, x, y + 1, n, m);Â
    // Lower right diagonal    int rightLowerDiagonal = collectGold(gold, x + 1, y + 1, n, m); Â
    // Return the maximum and store the value    return gold[x][y] + max(max(rightUpperDiagonal, rightLowerDiagonal), right); }Â
int getMaxGold(vector<vector<int>> gold, int n, int m){Â Â Â Â int maxGold = 0;Â
    for (int i = 0; i < n; i++) {Â
        // Recursive function call for ith row.        int goldCollected = collectGold(gold, i, 0, n, m);         maxGold = max(maxGold, goldCollected);    }Â
    return maxGold;}Â
// Driver Codeint main(){    vector<vector<int>> gold { {1, 3, 1, 5},        {2, 2, 4, 1},        {5, 0, 2, 3},        {0, 6, 1, 2}    };    int m = 4, n = 4;    cout << getMaxGold(gold, n, m);    return 0;} |
Java
// Java program to solve Gold Mine problemimport java.io.*;class GFG {  static int collectGold(int[][] gold, int x, int y,                         int n, int m)  {Â
    // Base condition.    if ((x < 0) || (x == n) || (y == m)) {      return 0;    }Â
    // Right upper diagonal    int rightUpperDiagonal      = collectGold(gold, x - 1, y + 1, n, m);Â
    // right    int right = collectGold(gold, x, y + 1, n, m);Â
    // Lower right diagonal    int rightLowerDiagonal      = collectGold(gold, x + 1, y + 1, n, m);Â
    // Return the maximum and store the value    return gold[x][y]      + Math.max(Math.max(rightUpperDiagonal,                          rightLowerDiagonal),                 right);  }Â
  static int getMaxGold(int[][] gold, int n, int m)  {    int maxGold = 0;Â
    for (int i = 0; i < n; i++) {Â
      // Recursive function call for ith row.      int goldCollected        = collectGold(gold, i, 0, n, m);      maxGold = Math.max(maxGold, goldCollected);    }Â
    return maxGold;  }  public static void main(String[] args)  {    int[][] gold = { { 1, 3, 1, 5 },                    { 2, 2, 4, 1 },                    { 5, 0, 2, 3 },                    { 0, 6, 1, 2 } };    int m = 4, n = 4;    System.out.println(getMaxGold(gold, n, m));  }}Â
// This code is contributed by Karandeep Singh. |
Python3
# Python program to solve Gold Mine problemdef collectGold(gold, x, y, n, m):Â
    # Base condition.    if ((x < 0) or (x == n) or (y == m)):         return 0Â
    # Right upper diagonal    rightUpperDiagonal = collectGold(gold, x - 1, y + 1, n, m)Â
     # right    right = collectGold(gold, x, y + 1, n, m)Â
    # Lower right diagonal    rightLowerDiagonal = collectGold(gold, x + 1, y + 1, n, m)Â
    # Return the maximum and store the value    return gold[x][y] + max(max(rightUpperDiagonal, rightLowerDiagonal), right) Â
Â
def getMaxGold(gold,n,m):Â
    maxGold = 0Â
    for i in range(n):Â
        # Recursive function call for ith row.        goldCollected = collectGold(gold, i, 0, n, m)        maxGold = max(maxGold, goldCollected)Â
    return maxGoldÂ
# Driver Codegold = [[1, 3, 1, 5],        [2, 2, 4, 1],        [5, 0, 2, 3],        [0, 6, 1, 2]]Â
m,n = 4,4print(getMaxGold(gold, n, m))Â
# This code is contributed by shinjanpatra. |
C#
// C# program to solve Gold Mine problemusing System;Â
public class GFG{Â
  static public int collectGold(int[,] gold, int x,                                 int y, int n, int m)  {         // Base condition.    if ((x < 0) || (x == n) || (y == m)) {      return 0;    }Â
    // Right upper diagonal    int rightUpperDiagonal = collectGold(gold, x - 1, y + 1, n, m);Â
    // right    int right = collectGold(gold, x, y + 1, n, m);Â
    // Lower right diagonal    int rightLowerDiagonal = collectGold(gold, x + 1, y + 1, n, m);Â
    // Return the maximum and store the value    return gold[x,y] + Math.Max(Math.Max(rightUpperDiagonal,                                          rightLowerDiagonal), right);  }Â
  static public int getMaxGold(int[,] gold, int n, int m){    int maxGold = 0;Â
    for (int i = 0; i < n; i++) {Â
      // Recursive function call for ith row.      int goldCollected = collectGold(gold, i, 0, n, m);      maxGold = Math.Max(maxGold, goldCollected);    }Â
    return maxGold;  }Â
  // Driver Code  static public void Main (){Â
    int[,] gold = new int[,] { { 1, 3, 1, 5 },                              { 2, 2, 4, 1 },                              { 5, 0, 2, 3 },                              { 0, 6, 1, 2 } };Â
    int m = 4, n = 4;    Console.Write(getMaxGold(gold, n, m));  }}Â
// This code is contributed by shruti456rawal |
Javascript
<script>Â
// JavaScript program to solve Gold Mine problemÂ
Â
function collectGold(gold,x,y,n,m) {Â
    // Base condition.    if ((x < 0) || (x == n) || (y == m)) {         return 0;    }   Â
    // Right upper diagonal    let rightUpperDiagonal = collectGold(gold, x - 1, y + 1, n, m); Â
     // right    let right = collectGold(gold, x, y + 1, n, m);Â
    // Lower right diagonal    let rightLowerDiagonal = collectGold(gold, x + 1, y + 1, n, m); Â
    // Return the maximum and store the value    return gold[x][y] + Math.max(Math.max(rightUpperDiagonal, rightLowerDiagonal), right); }Â
function getMaxGold(gold,n,m){Â Â Â Â maxGold = 0;Â
    for (i = 0; i < n; i++) {Â
        // Recursive function call for ith row.        goldCollected = collectGold(gold, i, 0, n, m);         maxGold = Math.max(maxGold, goldCollected);    }Â
    return maxGold;}Â
// Driver CodeÂ
let gold = [[1, 3, 1, 5],        [2, 2, 4, 1],        [5, 0, 2, 3],        [0, 6, 1, 2]];Â
let m = 4, n = 4;document.write(getMaxGold(gold, n, m));Â
// This code is contributed by shinjanpatra.</script> |
16
Time complexity: O(3N*M)
 Auxiliary Space: O(N*M)
Method 2: Memoization
Bottom-Up Approach: The second way is to take an extra space of size m*n and start computing values of states of right, right upper diagonal, and right bottom diagonal and store it in the 2d array.
C++
// C++ program to solve Gold Mine problem#include<bits/stdc++.h>using namespace std;Â
int collectGold(vector<vector<int>> gold, int x, int y, int n, int m, vector<vector<int>> &dp) {Â
    // Base condition.    if ((x < 0) || (x == n) || (y == m)) {         return 0;    }       if(dp[x][y] != -1){        return dp[x][y] ;    }Â
    // Right upper diagonal    int rightUpperDiagonal = collectGold(gold, x - 1, y + 1, n, m, dp); Â
     // right    int right = collectGold(gold, x, y + 1, n, m, dp);Â
    // Lower right diagonal    int rightLowerDiagonal = collectGold(gold, x + 1, y + 1, n, m, dp); Â
    // Return the maximum and store the value    return dp[x][y] = gold[x][y] + max(max(rightUpperDiagonal, rightLowerDiagonal), right); }Â
int getMaxGold(vector<vector<int>> gold, int n, int m){    int maxGold = 0;    // Initialize the dp vector    vector<vector<int>> dp(n, vector<int>(m, -1)) ;    for (int i = 0; i < n; i++) {Â
        // Recursive function call for ith row.        int goldCollected = collectGold(gold, i, 0, n, m, dp);         maxGold = max(maxGold, goldCollected);    }Â
    return maxGold;}Â
// Driver Codeint main(){    vector<vector<int>> gold { {1, 3, 1, 5},        {2, 2, 4, 1},        {5, 0, 2, 3},        {0, 6, 1, 2}    };    int m = 4, n = 4;    cout << getMaxGold(gold, n, m);    return 0;} |
Java
// Java program to solve Gold Mine problemimport java.io.*;class Gold {  static int collectGold(int[][] gold, int x, int y,                         int n, int m, int[][] dp)  {Â
    // Base condition.    if ((x < 0) || (x == n) || (y == m)) {      return 0;    }Â
    if (dp[x][y] != -1) {      return dp[x][y];    }Â
    // Right upper diagonal    int rightUpperDiagonal      = collectGold(gold, x - 1, y + 1, n, m, dp);Â
    // right    int right = collectGold(gold, x, y + 1, n, m, dp);Â
    // Lower right diagonal    int rightLowerDiagonal      = collectGold(gold, x + 1, y + 1, n, m, dp);Â
    // Return the maximum and store the value    return dp[x][y] = gold[x][y]      + Math.max(Math.max(rightUpperDiagonal,                          rightLowerDiagonal),                 right);  }Â
  static int getMaxGold(int[][] gold, int n, int m)  {    int maxGold = 0;    int[][] dp = new int[n][m];    for (int row = 0; row < n; row++) {      Arrays.fill(dp[row], -1);    }    for (int i = 0; i < n; i++) {Â
      // Recursive function call for ith row.      int goldCollected        = collectGold(gold, i, 0, n, m, dp);      maxGold = Math.max(maxGold, goldCollected);    }Â
    return maxGold;  }  public static void main(String[] args)  {    int[][] gold = { { 1, 3, 1, 5 },                    { 2, 2, 4, 1 },                    { 5, 0, 2, 3 },                    { 0, 6, 1, 2 } };    int m = 4, n = 4;    System.out.println(getMaxGold(gold, n, m));  }}Â
// This code is contributed by Karandeep Singh. |
Python3
# Python3 program to solve Gold Mine problemdef collectGold(gold, x, y, n, m, dp):Â
    # Base condition.    if ((x < 0) or (x == n) or (y == m)):        return 0Â
    if(dp[x][y] != -1):        return dp[x][y]Â
    # Right upper diagonal    rightUpperDiagonal = collectGold(gold, x - 1, y + 1, n, m, dp)Â
        # right    right = collectGold(gold, x, y + 1, n, m, dp)Â
    # Lower right diagonal    rightLowerDiagonal = collectGold(gold, x + 1, y + 1, n, m, dp)Â
    # Return the maximum and store the value    dp[x][y] = gold[x][y] + max(max(rightUpperDiagonal, rightLowerDiagonal), right)    return dp[x][y]  Â
def getMaxGold(gold,n,m):Â
    maxGold = 0    # Initialize the dp vector    dp = [[-1 for i in range(m)]for j in range(n)]         for i in range(n):Â
        # Recursive function call for ith row.        goldCollected = collectGold(gold, i, 0, n, m, dp)         maxGold = max(maxGold, goldCollected)Â
    return maxGoldÂ
# Driver CodeÂ
gold = [ [1, 3, 1, 5],        [2, 2, 4, 1],        [5, 0, 2, 3],        [0, 6, 1, 2] ]m,n = 4,4print(getMaxGold(gold, n, m))Â
# This code is contributed by Shinjanpatra |
C#
// C# program to solve Gold Mine problemusing System;Â
public class Gold{  static int collectGold(int[,] gold, int x, int y,                          int n, int m, int[,] dp)  {    // Base condition.    if ((x < 0) || (x == n) || (y == m))     {      return 0;    }Â
    if (dp[x,y] != -1)     {      return dp[x,y];    }Â
    // Right upper diagonal    int rightUpperDiagonal = collectGold(gold, x - 1, y + 1, n, m, dp);Â
    // right    int right = collectGold(gold, x, y + 1, n, m, dp);Â
    // Lower right diagonal    int rightLowerDiagonal = collectGold(gold, x + 1, y + 1, n, m, dp);Â
    // Return the maximum and store the value    return gold[x,y] + Math.Max(Math.Max(rightUpperDiagonal,                                          rightLowerDiagonal), right);  }Â
  static int getMaxGold(int[,] gold, int n, int m)  {    int maxGold = 0;    int[,] dp = new int[n, m];    for (int row = 0; row < n; row++)     {      for (int col = 0; col < m; col++)       {        dp[row,col] = -1;      }    }    for (int i = 0; i < n; i++)     {      // Recursive function call for ith row.      int goldCollected = collectGold(gold, i, 0, n, m, dp);      maxGold = Math.Max(maxGold, goldCollected);    }    return maxGold;  }  static public void Main ()  {    int[,] gold = { { 1, 3, 1, 5 },                   { 2, 2, 4, 1 },                   { 5, 0, 2, 3 },                   { 0, 6, 1, 2 } };    int m = 4, n = 4;    Console.Write(getMaxGold(gold, n, m));  }}Â
// This code is contributed by kothavvsaakash |
Javascript
<script>Â
// JavaScript program to solve Gold Mine problemfunction collectGold(gold, x, y, n, m, dp){Â
    // Base condition.    if ((x < 0) || (x == n) || (y == m)) {         return 0;    }       if(dp[x][y] != -1){        return dp[x][y] ;    }Â
    // Right upper diagonal    let rightUpperDiagonal = collectGold(gold, x - 1, y + 1, n, m, dp); Â
     // right    let right = collectGold(gold, x, y + 1, n, m, dp);Â
    // Lower right diagonal    let rightLowerDiagonal = collectGold(gold, x + 1, y + 1, n, m, dp); Â
    // Return the maximum and store the value    return dp[x][y] = gold[x][y] + Math.max(Math.max(rightUpperDiagonal, rightLowerDiagonal), right); }Â
function getMaxGold(gold,n,m){    let maxGold = 0;    // Initialize the dp vector    let dp = new Array(n);    for(let i = 0; i < n; i++)    {        dp[i] = new Array(m).fill(-1);    }    for (let i = 0; i < n; i++)     {Â
        // Recursive function call for ith row.        let goldCollected = collectGold(gold, i, 0, n, m, dp);         maxGold = Math.max(maxGold, goldCollected);    }Â
    return maxGold;}Â
// Driver CodeÂ
let gold = [ [1, 3, 1, 5],        [2, 2, 4, 1],        [5, 0, 2, 3],        [0, 6, 1, 2] ];let m = 4, n = 4;document.write(getMaxGold(gold, n, m));Â
// This code is contributed by ShinjanpatraÂ
</script> |
16
Time Complexity: O(m*n)
Auxiliary Space: O(m*n)
Method 3: Using Dp, Tabulation
Create a 2-D matrix goldTable[][]) of the same as given matrix mat[][]. If we observe the question closely, we can notice following.Â
- Amount of gold is positive, so we would like to cover maximum cells of maximum values under given constraints.
- In every move, we move one step toward right side. So we always end up in last column. If we are at the last column, then we are unable to move right
If we are at the first row or last column, then we are unable to move right-up so just assign 0 otherwise assign the value of goldTable[row-1][col+1] to right_up. If we are at the last row or last column, then we are unable to move right down so just assign 0 otherwise assign the value of goldTable[row+1][col+1] to right up.Â
Now find the maximum of right, right_up, and right_down and then add it with that mat[row][col]. At last, find the maximum of all rows and first column and return it.
C++
// C++ program to solve Gold Mine problem#include<bits/stdc++.h>using namespace std;Â
const int MAX = 100;Â
// Returns maximum amount of gold that can be collected// when journey started from first column and moves// allowed are right, right-up and right-downint getMaxGold(int gold[][MAX], int m, int n){    // Create a table for storing intermediate results    // and initialize all cells to 0. The first row of    // goldMineTable gives the maximum gold that the miner    // can collect when starts that row    int goldTable[m][n];    memset(goldTable, 0, sizeof(goldTable));Â
    for (int col=n-1; col>=0; col--)    {        for (int row=0; row<m; row++)        {            // Gold collected on going to the cell on the right(->)            int right = (col==n-1)? 0: goldTable[row][col+1];Â
            // Gold collected on going to the cell to right up (/)            int right_up = (row==0 || col==n-1)? 0:                            goldTable[row-1][col+1];Â
            // Gold collected on going to the cell to right down (\)            int right_down = (row==m-1 || col==n-1)? 0:                             goldTable[row+1][col+1];Â
            // Max gold collected from taking either of the            // above 3 paths            goldTable[row][col] = gold[row][col] +                              max(right, max(right_up, right_down));                                                             }    }Â
    // The max amount of gold collected will be the max    // value in first column of all rows    int res = goldTable[0][0];    for (int i=1; i<m; i++)        res = max(res, goldTable[i][0]);    return res;}Â
// Driver Codeint main(){    int gold[MAX][MAX]= { {1, 3, 1, 5},        {2, 2, 4, 1},        {5, 0, 2, 3},        {0, 6, 1, 2}    };    int m = 4, n = 4;    cout << getMaxGold(gold, m, n);    return 0;} |
Java
// Java program to solve Gold Mine problemimport java.util.Arrays;Â
class GFG {         static final int MAX = 100;         // Returns maximum amount of gold that     // can be collected when journey started     // from first column and moves allowed     // are right, right-up and right-down    static int getMaxGold(int gold[][],                               int m, int n)    {                 // Create a table for storing         // intermediate results and initialize        // all cells to 0. The first row of        // goldMineTable gives the maximum         // gold that the miner can collect         // when starts that row        int goldTable[][] = new int[m][n];                 for(int[] rows:goldTable)            Arrays.fill(rows, 0);             for (int col = n-1; col >= 0; col--)        {            for (int row = 0; row < m; row++)            {                                 // Gold collected on going to                 // the cell on the right(->)                int right = (col == n-1) ? 0                        : goldTable[row][col+1];                     // Gold collected on going to                 // the cell to right up (/)                int right_up = (row == 0 ||                               col == n-1) ? 0 :                        goldTable[row-1][col+1];                     // Gold collected on going to                 // the cell to right down (\)                int right_down = (row == m-1                            || col == n-1) ? 0 :                          goldTable[row+1][col+1];                     // Max gold collected from taking                // either of the above 3 paths                goldTable[row][col] = gold[row][col]                 + Math.max(right, Math.max(right_up,                                        right_down));                                                                     }        }             // The max amount of gold collected will be        // the max value in first column of all rows        int res = goldTable[0][0];                 for (int i = 1; i < m; i++)            res = Math.max(res, goldTable[i][0]);                     return res;    }         //driver code    public static void main(String arg[])    {        int gold[][]= { {1, 3, 1, 5},                        {2, 2, 4, 1},                        {5, 0, 2, 3},                        {0, 6, 1, 2} };                                 int m = 4, n = 4;                 System.out.print(getMaxGold(gold, m, n));    }}Â
// This code is contributed by Anant Agarwal. |
Python3
# Python program to solve# Gold Mine problemÂ
MAX = 100Â
# Returns maximum amount of# gold that can be collected# when journey started from# first column and moves# allowed are right, right-up# and right-downdef getMaxGold(gold, m, n):Â
    # Create a table for storing    # intermediate results    # and initialize all cells to 0.    # The first row of    # goldMineTable gives the    # maximum gold that the miner    # can collect when starts that row    goldTable = [[0 for i in range(n)]                        for j in range(m)]Â
    for col in range(n-1, -1, -1):        for row in range(m):Â
            # Gold collected on going to            # the cell on the right(->)            if (col == n-1):                right = 0            else:                right = goldTable[row][col+1]Â
            # Gold collected on going to            # the cell to right up (/)            if (row == 0 or col == n-1):                right_up = 0            else:                right_up = goldTable[row-1][col+1]Â
            # Gold collected on going to            # the cell to right down (\)            if (row == m-1 or col == n-1):                right_down = 0            else:                right_down = goldTable[row+1][col+1]Â
            # Max gold collected from taking            # either of the above 3 paths            goldTable[row][col] = gold[row][col] + max(right, right_up, right_down)                                                                # The max amount of gold    # collected will be the max    # value in first column of all rows    res = goldTable[0][0]    for i in range(1, m):        res = max(res, goldTable[i][0])Â
    return res     # Driver codegold = [[1, 3, 1, 5],    [2, 2, 4, 1],    [5, 0, 2, 3],    [0, 6, 1, 2]]Â
m = 4n = 4Â
print(getMaxGold(gold, m, n))Â
# This code is contributed# by Soumen Ghosh.             |
C#
// C# program to solve Gold Mine problem using System; Â
class GFG { Â Â Â Â static int MAX = 100; Â
    // Returns maximum amount of gold that     // can be collected when journey started    // from first column and moves allowed are     // right, right-up and right-down     static int getMaxGold(int[,] gold,                             int m, int n)     {                  // Create a table for storing intermediate         // results and initialize all cells to 0.         // The first row of goldMineTable gives        // the maximum gold that the miner         // can collect when starts that row         int[,] goldTable = new int[m, n];                  for(int i = 0; i < m; i++)            for(int j = 0; j < n; j++)                goldTable[i, j] = 0;             for (int col = n - 1; col >= 0; col--)         {             for (int row = 0; row < m; row++)             {                 // Gold collected on going to                 // the cell on the right(->)                 int right = (col == n - 1) ? 0 :                            goldTable[row, col + 1];                      // Gold collected on going to                 // the cell to right up (/)                 int right_up = (row == 0 || col == n - 1)                             ? 0 : goldTable[row-1,col+1];                      // Gold collected on going                 // to the cell to right down (\)                 int right_down = (row == m - 1 || col == n - 1)                                 ? 0 : goldTable[row + 1, col + 1];                      // Max gold collected from taking                 // either of the above 3 paths                 goldTable[row, col] = gold[row, col] +                                 Math.Max(right, Math.Max(right_up,                                                     right_down));             }         }              // The max amount of gold collected will be the max         // value in first column of all rows         int res = goldTable[0, 0];         for (int i = 1; i < m; i++)             res = Math.Max(res, goldTable[i, 0]);         return res;     }          // Driver Code     static void Main()     {         int[,] gold = new int[,]{{1, 3, 1, 5},                                 {2, 2, 4, 1},                                 {5, 0, 2, 3},                                 {0, 6, 1, 2}                                 };         int m = 4, n = 4;         Console.Write(getMaxGold(gold, m, n));     }}Â
// This code is contributed by DrRoot_ |
PHP
<?php// Php program to solve Gold Mine problem Â
// Returns maximum amount of gold that // can be collected when journey started // from first column and moves allowed are // right, right-up and right-down function getMaxGold($gold, $m, $n){    $MAX = 100 ;         // Create a table for storing intermediate     // results and initialize all cells to 0.     // The first row of goldMineTable gives the     // maximum gold that the miner can collect     // when starts that row     $goldTable = array(array());    for ($i = 0; $i < $m ; $i ++)        for($j = 0; $j < $n ; $j ++)            $goldTable[$i][$j] = 0 ;                 for ($col = $n - 1; $col >= 0 ; $col--)     {        for ($row = 0 ; $row < $m ; $row++)        {Â
            // Gold collected on going to             // the cell on the right(->)             if ($col == $n - 1)                $right = 0 ;            else                $right = $goldTable[$row][$col + 1];Â
            // Gold collected on going to             // the cell to right up (/)             if ($row == 0 or $col == $n - 1)                 $right_up = 0 ;            else                $right_up = $goldTable[$row - 1][$col + 1]; Â
            // Gold collected on going to             // the cell to right down (\)             if ($row == $m - 1 or $col == $n - 1)                $right_down = 0 ;            else                $right_down = $goldTable[$row + 1][$col + 1];Â
            // Max gold collected from taking             // either of the above 3 paths             $goldTable[$row][$col] = $gold[$row][$col] +                                  max($right, $right_up,                                              $right_down);         }    }         // The max amount of gold collected will be the     // max value in first column of all rows     $res = $goldTable[0][0] ;    for ($i = 0; $i < $m; $i++)         $res = max($res, $goldTable[$i][0]); Â
    return $res;}     // Driver code $gold = array(array(1, 3, 1, 5),               array(2, 2, 4, 1),               array(5, 0, 2, 3),               array(0, 6, 1, 2));Â
$m = 4 ;$n = 4 ;Â
echo getMaxGold($gold, $m, $n) ;Â
// This code is contributed by Ryuga?> |
Javascript
<script>Â
    // JavaScript program to solve Gold Mine problem         let MAX = 100;          // Returns maximum amount of gold that    // can be collected when journey started    // from first column and moves allowed    // are right, right-up and right-down    function getMaxGold(gold, m, n)    {                  // Create a table for storing        // intermediate results and initialize        // all cells to 0. The first row of        // goldMineTable gives the maximum        // gold that the miner can collect        // when starts that row        let goldTable = new Array(m);                 for(let i = 0; i < m; i++)        {            goldTable[i] = new Array(n);            for(let j = 0; j < n; j++)            {                goldTable[i][j] = 0;            }        }              for (let col = n-1; col >= 0; col--)        {            for (let row = 0; row < m; row++)            {                                  // Gold collected on going to                // the cell on the right(->)                let right = (col == n-1) ? 0                        : goldTable[row][col+1];                      // Gold collected on going to                // the cell to right up (/)                let right_up = (row == 0 ||                               col == n-1) ? 0 :                        goldTable[row-1][col+1];                      // Gold collected on going to                // the cell to right down (\)                let right_down = (row == m-1                            || col == n-1) ? 0 :                          goldTable[row+1][col+1];                      // Max gold collected from taking                // either of the above 3 paths                goldTable[row][col] = gold[row][col]                 + Math.max(right, Math.max(right_up,                                       right_down));                                                                      }        }              // The max amount of gold collected will be        // the max value in first column of all rows        let res = goldTable[0][0];                  for (let i = 1; i < m; i++)            res = Math.max(res, goldTable[i][0]);                      return res;    }         let gold = [ [1, 3, 1, 5],                  [2, 2, 4, 1],                  [5, 0, 2, 3],                  [0, 6, 1, 2] ];                              let m = 4, n = 4;Â
    document.write(getMaxGold(gold, m, n));Â
</script> |
16
Time Complexity: O(m*n)Â
Auxiliary Space: O(m*n)
Space Complex Solution: In the above-given method we require O(m x n) space. This will not be suitable if the length of strings is greater than 2000 as it can only create 2D array of 2000 x 2000. To fill a row in DP array we require only one row the upper row. For example, if we are filling the i = 10 rows in DP array we require only values of 9th row. So we simply create a DP array of 2 x str1 length. This approach reduces the space complexity. Here is the Python3 implementation of the above-mentioned problem.
C++
// C++ program to solve// Gold Mine problem#include <bits/stdc++.h>using namespace std;Â
int MAX = 100;Â
// Returns maximum amount of// gold that can be collected// when journey started from// first column and moves// allowed are right, right-up// and right-downint getMaxGold(vector<vector<int>> gold, int m, int n){  // Create a table for storing  // intermediate results  // and initialize all cells to 0.  // The first row of  // goldMineTable gives the  // maximum gold that the miner  // can collect when starts that row  int goldTable[m][2];  for (int i = 0; i < m; i++)  {    goldTable[i][0] = 0;    goldTable[i][1] = 0;  }Â
  for (int col = n - 1; col > -1; col--)  {    for (int row = 0; row < m; row++)    {      int right, right_up, right_down;      // Gold collected on going to      // the cell on the right(->)      if (col == n-1)        right = 0;      else        right = goldTable[row][(col+1)%2];Â
      // Gold collected on going to      // the cell to right up (/)      if (row == 0 || col == n-1)        right_up = 0;      else        right_up = goldTable[row-1][(col+1)%2];Â
      // Gold collected on going to      // the cell to right down (\)      if (row == m-1 || col == n-1)        right_down = 0;      else        right_down = goldTable[row+1][(col+1)%2];Â
      // Max gold collected from taking      // either of the above 3 paths      goldTable[row][col%2] = gold[row][col] + max(right, max(right_up, right_down));    }  }Â
  // The max amount of gold  // collected will be the max  // value in first column of all rows  int res = goldTable[0][0];  for (int i = 1; i < m; i++)     res = max(res, goldTable[i][0]);Â
  return res;}Â
// Driver codeint main(){Â Â int m = 4;Â Â int n = 4;Â
  vector<vector<int>> gold = {{ 1, 3, 1, 5},                              {2, 2, 4, 1},                              {5, 0, 2, 3},                              {0, 6, 1, 2}};Â
Â
  cout << getMaxGold(gold, m, n) << endl;}Â
// This code is contributed// by phasing17Â Â Â Â Â Â |
Java
// Java program to solve// Gold Mine problemimport java.io.*;class GFG{    static int MAX = 100;         // Returns maximum amount of    // gold that can be collected    // when journey started from    // first column and moves    // allowed are right, right-up    // and right-down    static int getMaxGold(int gold[][], int m, int n)    {      // Create a table for storing      // intermediate results      // and initialize all cells to 0.      // The first row of      // goldMineTable gives the      // maximum gold that the miner      // can collect when starts that row      int goldTable[][] = new int[m][2];      for (int i = 0; i < m; i++)      {        goldTable[i][0] = 0;        goldTable[i][1] = 0;      }           for (int col = n - 1; col > -1; col--)      {        for (int row = 0; row < m; row++)        {          int right, right_up, right_down;          // Gold collected on going to          // the cell on the right(->)          if (col == n-1)            right = 0;          else            right = goldTable[row][(col+1)%2];               // Gold collected on going to          // the cell to right up (/)          if (row == 0 || col == n-1)            right_up = 0;          else            right_up = goldTable[row-1][(col+1)%2];               // Gold collected on going to          // the cell to right down (\)          if (row == m-1 || col == n-1)            right_down = 0;          else            right_down = goldTable[row+1][(col+1)%2];               // Max gold collected from taking          // either of the above 3 paths          goldTable[row][col%2] = gold[row][col] + Math.max(right, Math.max(right_up, right_down));        }      }           // The max amount of gold      // collected will be the max      // value in first column of all rows      int res = goldTable[0][0];      for (int i = 1; i < m; i++)         res = Math.max(res, goldTable[i][0]);           return res;    }         // Driver code    public static void main(String[] args)    {      int m = 4;      int n = 4;           int[][] gold = {{ 1, 3, 1, 5},                                  {2, 2, 4, 1},                                  {5, 0, 2, 3},                                  {0, 6, 1, 2}};                System.out.println(getMaxGold(gold, m, n));    }}Â
// This code is contributed// by phasing17Â Â Â Â Â Â |
Python3
# Python program to solve# Gold Mine problemÂ
MAX = 100Â
# Returns maximum amount of# gold that can be collected# when journey started from# first column and moves# allowed are right, right-up# and right-downdef getMaxGold(gold, m, n):Â
    # Create a table for storing    # intermediate results    # and initialize all cells to 0.    # The first row of    # goldMineTable gives the    # maximum gold that the miner    # can collect when starts that row    goldTable = [[0 for i in range(2)]                        for j in range(m)]Â
    for col in range(n-1, -1, -1):        for row in range(m):Â
            # Gold collected on going to            # the cell on the right(->)            if (col == n-1):                right = 0            else:                right = goldTable[row][(col+1)%2]Â
            # Gold collected on going to            # the cell to right up (/)            if (row == 0 or col == n-1):                right_up = 0            else:                right_up = goldTable[row-1][(col+1)%2]Â
            # Gold collected on going to            # the cell to right down (\)            if (row == m-1 or col == n-1):                right_down = 0            else:                right_down = goldTable[row+1][(col+1)%2]Â
            # Max gold collected from taking            # either of the above 3 paths            goldTable[row][col%2] = gold[row][col] + max(right, right_up, right_down)                                                                 # The max amount of gold    # collected will be the max    # value in first column of all rows    res = goldTable[0][0]    for i in range(1, m):        res = max(res, goldTable[i][0])Â
    return res     # Driver codegold = [[1, 3, 1, 5],    [2, 2, 4, 1],    [5, 0, 2, 3],    [0, 6, 1, 2]]Â
m = 4n = 4Â
print(getMaxGold(gold, m, n))Â
# This code is contributed# by Bhagirath Sarvaiya.           |
C#
// C# program to solve// Gold Mine problemusing System;using System.Collections.Generic;Â
class GFG{    int MAX = 100;         // Returns maximum amount of    // gold that can be collected    // when journey started from    // first column and moves    // allowed are right, right-up    // and right-down    static int getMaxGold(int[,] gold, int m, int n)    {      // Create a table for storing      // intermediate results      // and initialize all cells to 0.      // The first row of      // goldMineTable gives the      // maximum gold that the miner      // can collect when starts that row      int[,] goldTable = new int[m, 2];      for (int i = 0; i < m; i++)      {        goldTable[i, 0] = 0;        goldTable[i, 1] = 0;      }           for (int col = n - 1; col > -1; col--)      {        for (int row = 0; row < m; row++)        {          int right, right_up, right_down;          // Gold collected on going to          // the cell on the right(->)          if (col == n-1)            right = 0;          else            right = goldTable[row, (col+1)%2];               // Gold collected on going to          // the cell to right up (/)          if (row == 0 || col == n-1)            right_up = 0;          else            right_up = goldTable[row-1, (col+1)%2];               // Gold collected on going to          // the cell to right down (\)          if (row == m-1 || col == n-1)            right_down = 0;          else            right_down = goldTable[row+1, (col+1)%2];               // Max gold collected from taking          // either of the above 3 paths          goldTable[row, col%2] = gold[row, col] + Math.Max(right, Math.Max(right_up, right_down));        }      }           // The max amount of gold      // collected will be the max      // value in first column of all rows      int res = goldTable[0, 0];      for (int i = 1; i < m; i++)         res = Math.Max(res, goldTable[i, 0]);           return res;    }         // Driver code    public static void Main(string[] args)    {      int m = 4;      int n = 4;           int[,] gold = {{ 1, 3, 1, 5},                                  {2, 2, 4, 1},                                  {5, 0, 2, 3},                                  {0, 6, 1, 2}};               Console.WriteLine(getMaxGold(gold, m, n));    }}Â
// This code is contributed// by phasing17Â Â Â Â Â Â |
Javascript
// JS program to solve// Gold Mine problemÂ
let MAX = 100Â
// Returns maximum amount of// gold that can be collected// when journey started from// first column and moves// allowed are right, right-up// and right-downfunction getMaxGold(gold, m, n){    // Create a table for storing    // intermediate results    // and initialize all cells to 0.    // The first row of    // goldMineTable gives the    // maximum gold that the miner    // can collect when starts that row    let goldTable = new Array(m);    for (var i = 0; i < m; i++)        goldTable[i] = new Array(2).fill(0);         for (var col = n - 1; col > -1; col--)    {        for (var row = 0; row < m; row++)        {            let right, right_up, right_down;            // Gold collected on going to            // the cell on the right(->)            if (col == n-1)                right = 0;            else                right = goldTable[row][(col+1)%2]Â
            // Gold collected on going to            // the cell to right up (/)            if (row == 0 || col == n-1)                right_up = 0            else                right_up = goldTable[row-1][(col+1)%2]Â
            // Gold collected on going to            // the cell to right down (\)            if (row == m-1 || col == n-1)                right_down = 0            else                right_down = goldTable[row+1][(col+1)%2]Â
            // Max gold collected from taking            // either of the above 3 paths            goldTable[row][col%2] = gold[row][col] + Math.max(right, Math.max(right_up, right_down))        }    }                                                                 // The max amount of gold    // collected will be the max    // value in first column of all rows    let res = goldTable[0][0]    for (var i = 1; i < m; i++)         res = Math.max(res, goldTable[i][0])Â
    return res}     // Driver codelet gold = [[1, 3, 1, 5],    [2, 2, 4, 1],    [5, 0, 2, 3],    [0, 6, 1, 2]]Â
let m = 4let n = 4Â
console.log(getMaxGold(gold, m, n))Â
// This code is contributed// by phasing17Â Â Â Â Â Â |
16
Time Complexity: O(m*n)Â
Auxiliary Space: O(m*2)
->Directed Array Approach
Time Complexity – O(m*n)
Space Complexity – O(m*n)
C++
#include <bits/stdc++.h>using namespace std;Â
int dx[3] = { -1, 0, 1 };int dy[3] = { -1, -1, -1 };Â
bool isValid(int x, int y, int n, int m){Â Â Â Â if (x >= 0 && x < n && y >= 0 && y < m)Â Â Â Â Â Â Â Â return true;Â Â Â Â return false;}Â
int maxGold(int n, int m, vector<vector<int> > M){Â Â Â Â int dp[n][m];Â
    // initialisation of first col    for (int i = 0; i < n; i++)        dp[i][0] = M[i][0];Â
    for (int j = 1; j < m; j++) {        for (int i = 0; i < n; i++) {            int mx = INT_MIN;            for (int k = 0; k < 3; k++) {                int x = i + dx[k];                int y = j + dy[k];Â
                if (isValid(x, y, n, m))                    mx = max(mx, dp[x][y] + M[i][j]);            }            dp[i][j] = mx;        }    }Â
    int ans = INT_MIN;Â
    for (int i = 0; i < n; i++) {        ans = max(ans, dp[i][m - 1]);    }    return ans;}Â
int main(){Â
    int n = 4;    int m = 4;Â
    vector<vector<int> > gold = { { 1, 3, 1, 5 },                                  { 2, 2, 4, 1 },                                  { 5, 0, 2, 3 },                                  { 0, 6, 1, 2 } };Â
    cout << "Max Amount of gold collected = "         << maxGold(n, m, gold);    return 0;} |
Java
// java code to implement the approachÂ
import java.util.*;Â
class GFG {  static int[] dx    = new int[] { -1, 0, 1 }; // used to traverse grid  static int[] dy    = new int[] { -1, -1, -1 }; // used to traverse gridÂ
  // method to check if given point is valid or not  static boolean isValid(int x, int y, int n, int m)  {    if (x >= 0 && x < n && y >= 0 && y < m)      return true;    return false;  }Â
  // method to find the max amount of gold that can be  // collected  static int maxGold(int n, int m, int[][] M)  {    int[][] dp = new int[n][m];Â
    // initialisation of first col    for (int i = 0; i < n; i++)      dp[i][0] = M[i][0];Â
    // Dynamic programming    for (int j = 1; j < m; j++) {      for (int i = 0; i < n; i++) {        int mx = Integer.MIN_VALUE;        for (int k = 0; k < 3; k++) {          int x = i + dx[k];          int y = j + dy[k];Â
          if (isValid(x, y, n, m))            mx = Math.max(mx,                          dp[x][y] + M[i][j]);        }        dp[i][j] = mx;      }    }Â
    int ans = Integer.MIN_VALUE;Â
    // find max value from last column of dp table    for (int i = 0; i < n; i++) {      ans = Math.max(ans, dp[i][m - 1]);    }    return ans;  }Â
  // Driver code  public static void main(String[] args)  {    int n = 4;    int m = 4;Â
    int[][] gold = new int[][] { { 1, 3, 1, 5 },                                { 2, 2, 4, 1 },                                { 5, 0, 2, 3 },                                { 0, 6, 1, 2 } };Â
    // Function call    System.out.println("Max Amount of gold collected = "                       + maxGold(n, m, gold));  }}Â
// This code is contributed by phasing17. |
Python3
# Python3 code to implement the approachdx = [-1, 0, 1]dy = [-1, -1, -1]Â
# This function checks if a given coordinate is validdef is_valid(x, y, n, m):    if x >= 0 and x < n and y >= 0 and y < m:        return True    return FalseÂ
# This function finds the maximum gold quantitydef max_gold(n, m, M):         # Initializing dp    dp = [[0 for j in range(m)] for i in range(n)]    for i in range(n):        dp[i][0] = M[i][0]             # Building the dp    for j in range(1, m):        for i in range(n):            mx = float('-inf')            for k in range(3):                x = i + dx[k]                y = j + dy[k]                if is_valid(x, y, n, m):                    mx = max(mx, dp[x][y] + M[i][j])            dp[i][j] = mx    ans = float('-inf')         # Getting the final answer    for i in range(n):        ans = max(ans, dp[i][m - 1])    return ansÂ
Â
# Driver coden = 4m = 4gold = [    [1, 3, 1, 5],    [2, 2, 4, 1],    [5, 0, 2, 3],    [0, 6, 1, 2],]Â
# Function callprint("Max Amount of gold collected = ", max_gold(n, m, gold))Â
# This code is contributed by phasing17 |
C#
using System;using System.Collections.Generic;Â
class GFG {  static int[] dx    = new int[] { -1, 0, 1 }; // used to traverse grid  static int[] dy    = new int[] { -1, -1, -1 }; // used to traverse gridÂ
  // method to check if given point is valid or not  static bool isValid(int x, int y, int n, int m)  {    if (x >= 0 && x < n && y >= 0 && y < m)      return true;    return false;  }Â
  // method to find the max amount of gold that can be  // collected  static int maxGold(int n, int m, int[][] M)  {    int[][] dp = new int[n][];    for (int i = 0; i < n; i++)      dp[i] = new int[m];Â
    // initialisation of first col    for (int i = 0; i < n; i++)      dp[i][0] = M[i][0];Â
    // Dynamic programming    for (int j = 1; j < m; j++) {      for (int i = 0; i < n; i++) {        int mx = Int32.MinValue;        for (int k = 0; k < 3; k++) {          int x = i + dx[k];          int y = j + dy[k];Â
          if (isValid(x, y, n, m))            mx = Math.Max(mx,                          dp[x][y] + M[i][j]);        }        dp[i][j] = mx;      }    }Â
    int ans = Int32.MinValue;Â
    // find max value from last column of dp table    for (int i = 0; i < n; i++) {      ans = Math.Max(ans, dp[i][m - 1]);    }    return ans;  }Â
  // Driver code  static void Main(string[] args)  {    int n = 4;    int m = 4;Â
    int[][] gold      = new int[][] { new int[] { 1, 3, 1, 5 },                     new int[] { 2, 2, 4, 1 },                     new int[] { 5, 0, 2, 3 },                     new int[] { 0, 6, 1, 2 } };Â
    // Function call    Console.WriteLine("Max Amount of gold collected = "                      + maxGold(n, m, gold));  }}Â
// This code is contributed by phasing17. |
Javascript
// JavaScript implementation of the above approachÂ
const dx = [-1, 0, 1];const dy = [-1, -1, -1];Â
// This function checks if a given point coordinate location is validfunction isValid(x, y, n, m) {Â Â Â Â if (x >= 0 && x < n && y >= 0 && y < m) {Â Â Â Â Â Â Â Â return true;Â Â Â Â }Â Â Â Â return false;}Â
function maxGold(n, m, M) {         // Initializing DP array          let dp = new Array(n);    for (let i = 0; i < dp.length; i++) {        dp[i] = new Array(m);    }Â
    // initialisation of first col    for (let i = 0; i < n; i++) {        dp[i][0] = M[i][0];    }              // Performing DP    for (let j = 1; j < m; j++) {        for (let i = 0; i < n; i++) {            let mx = Number.MIN_SAFE_INTEGER;            for (let k = 0; k < 3; k++) {                let x = i + dx[k];                let y = j + dy[k];Â
                if (isValid(x, y, n, m)) {                    mx = Math.max(mx, dp[x][y] + M[i][j]);                }            }            dp[i][j] = mx;        }    }Â
    let ans = Number.MIN_SAFE_INTEGER;         // Getting the answer    for (let i = 0; i < n; i++) {        ans = Math.max(ans, dp[i][m - 1]);    }    return ans;}Â
// Driver Codeconst n = 4;const m = 4;Â
const gold = [    [1, 3, 1, 5],    [2, 2, 4, 1],    [5, 0, 2, 3],    [0, 6, 1, 2],];Â
console.log("Max Amount of gold collected = " + maxGold(n, m, gold));Â
Â
// This code is contributed by phasing17 |
Max Amount of gold collected = 16
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!
