# Program to find maximum coins we can get from disappearing coins matrix in Python

Suppose we have a 2D matrix where each cell matrix[r, c] represents the number of coins present in that cell. When we pick up coins from matrix[r, c], all the coins on row (r - 1) and (r + 1) will disappear, as well as the coins at the two cells matrix[r, c + 1] and matrix[r, c - 1]. We have to find the maximum number of coins we can collect.

So, if the input is like

 2 8 7 6 10 10 4 2 5 9 2 3

then the output will be 26 because we can pick cells with the coins 8, 6, and 9 and 3, so total is 26.

To solve this, we will follow these steps −

• Define a function getmax() . This will take arr
• prev_max := 0
• curr_max := 0
• res := 0
• for each num in arr, do
• temp := curr_max
• curr_max := num + prev_max
• prev_max := maximum of temp and prev_max
• res := maximum of res and curr_max
• return res
• From the main method do the following −
• if matrix is empty, then
• return 0
• m := row count of matrix
• n := column count of matrix
• row_sum := an array of size m and fill with 0
• for i in range 0 to m - 1, do
• row_sum[i] := getmax(matrix[i])
• return getmax(row_sum)

## Example

Let us see the following implementation to get better understanding −

def getmax(arr):
prev_max, curr_max = 0, 0
res = 0
for num in arr:
temp = curr_max
curr_max = num + prev_max
prev_max = max(temp, prev_max)
res = max(res, curr_max)
return res

def solve(matrix):
if not matrix:
return 0
m, n = len(matrix), len(matrix)
row_sum = [0 for _ in range(m)]
for i in range(m):
row_sum[i] = getmax(matrix[i])
return getmax(row_sum)

matrix = [
[2, 8, 7, 6],
[10, 10, 4, 2],
[5, 9, 2, 3]
]
print(solve(matrix))

## Input

[
[2, 8, 7, 6],
[10, 10, 4, 2],
[5, 9, 2, 3]
]

## Output

26