Problem to Find Out the Maximum Number of Coins that Can be Collected in Python


Suppose, we have a 2D matrix in which the cells represent the number of coins in it. There are our two friends to collect coins, and they are placed at the top left corner and at the top right corner at the start. They follow these rules:

  • From cell (i, j), a coin-collector can move to cell (i + 1, j - 1), (i + 1, j), or (i + 1, j + 1).

  • Upon reaching a cell they collect all the coins available making the cell empty.

  • The collectors may choose to stay at one cell, but the coins in any cell can be collected only once.

We have to find the maximum number of coins that can be collected.

So, if the input is like

0410
3140
2511
3000

then the output will be 17.

To solve this, we will follow these steps −

  • A := the input matrix

  • R := row count of A

  • C := column count of A

  • Define a function dp() . This will take r, c1, c2

    • if r is same as R, then

      • return 0

    • ans := A[r, c1] +(if c1 is not equal to c2, then 1 else 0) * A[r, c2]

    • base := ans

    • for each nc1 in [c1 − 1, c1, c1 + 1], do

      • for each nc2 in [c2 − 1, c2, c2 + 1], do

        • if 0 <= nc1 < C and 0 <= nc2 < C, then

          • ans := maximum of ans and (base + dp(r + 1, nc1, nc2))

    • return ans

  • return dp(0, 0, C − 1)

Let us see the following implementation to get better understanding −

Example

 Live Demo

class Solution:
   def solve(self, A):
      R, C = len(A), len(A[0])
      def dp(r, c1, c2):
         if r == R:
            return 0
         ans = base = A[r][c1] + (c1 != c2) * A[r][c2]
         for nc1 in [c1 − 1, c1, c1 + 1]:
            for nc2 in [c2 − 1, c2, c2 + 1]:
               if 0 <= nc1 < C and 0 <= nc2 < C:
                  ans = max(ans, base + dp(r + 1, nc1, nc2))
         return ans
      return dp(0, 0, C − 1)
ob = Solution()
print(ob.solve([
   [0, 4, 1, 0],
   [3, 1, 4, 0],
   [2, 5, 1, 1],
   [3, 0, 0, 0]
]))

Input

[
   [0, 4, 1, 0],
   [3, 1, 4, 0],
   [2, 5, 1, 1],
   [3, 0, 0, 0]
]

Output

17

Updated on: 26-Dec-2020

66 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements