Program to find maximum number of coins we can collect in Python


Suppose we have a 2D matrix where each cell stores some coins. If we start from [0,0], and can only move right or down, we have to find the maximum number of coins we can collect by the bottom right corner.

So, if the input is like

1
4
2
2
0
0
0
5

then the output will be 14, as we take the path: [1, 4, 2, 2, 5]

To solve this, we will follow these steps−

  • for r in range 1 to row count of A, do

    • A[r, 0] := A[r, 0] + A[r-1, 0]

  • for c in range 1 to column count of A, do

    • A[0, c] := A[0, c] + A[0, c-1]

    • for r in range 1 to size of A, do

    • for c in range 1 to size of A[0], do

    • A[r, c] = A[r, c] + maximum of (A[r-1, c] and A[r, c-1]

  • return value of bottom right corner of A

Let us see the following implementation to get better understanding−

Example

 Live Demo

class Solution:
   def solve(self, A):
      for r in range(1, len(A)):
         A[r][0] += A[r-1][0]
      for c in range(1, len(A[0])):
         A[0][c] += A[0][c-1]
      for r in range(1, len(A)):
         for c in range(1, len(A[0])):
            A[r][c] += max(A[r-1][c], A[r][c-1])
      return A[-1][-1]
ob = Solution()
matrix = [ [1, 4, 2, 2], [6, 0, 0, 5] ]
print(ob.solve(matrix))

Input

matrix = [
   [1, 4, 2, 2],
   [6, 0, 0, 5]
]

Output

14

Updated on: 05-Oct-2020

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements