714128. Maximum Number of coins

Hard

Maximum Number of Coins

Summary

The problem is to find the maximum number of coins that can be placed on a grid such that no two coins overlap and they cover the entire grid. The input is given as an n x m grid where 0 represents empty cells and 1 represents coin positions.

This problem involves dynamic programming, matrix manipulation, and data structures concepts.

Detailed Explanation

The problem can be solved by using a bottom-up dynamic programming approach. We initialize a 2D array dp of size (n+1) x (m+1) where dp[i][j] represents the maximum number of coins that can be placed in the sub-grid from (0,0) to (i,j).

We iterate through the grid from bottom-up and for each cell (i,j), we consider two possibilities:

  • If the current cell is empty (grid[i][j] == 0), then we have two options: either place a coin at this position or not. We take the maximum of these two options.
  • If the current cell already has a coin (grid[i][j] == 1), then we cannot place another coin here, so we consider only one option (i.e., do not place a coin).

The recurrence relation is: dp[i][j] = max(dp[i-1][j], dp[i][j-1]) + (1 if grid[i][j] == 0 else 0)

Finally, the maximum number of coins that can be placed on the entire grid is stored in dp[n][m].

Here's a step-by-step breakdown:

for i from n to 0
  for j from m to 0
    if grid[i][j] == 0
      dp[i][j] = max(dp[i-1][j], dp[i][j-1]) + 1
    else
      dp[i][j] = dp[i-1][j]

The time complexity of this approach is O(nm) and the space complexity is also O(nm).

Optimized Solutions

Java

View on GeeksforGeeks
public class Main {
    public static int maxCoins(int[][] grid) {
        int n = grid.length;
        int m = grid[0].length;
        int[][] dp = new int[n+1][m+1];
        
        for (int i = 0; i <= n; i++) {
            for (int j = 0; j <= m; j++) {
                if (grid[i][j] == 0) {
                    dp[i][j] = Math.max(dp[i-1][j], dp[i][j-1]) + 1;
                } else {
                    dp[i][j] = dp[i-1][j];
                }
            }
        }
        
        return dp[n][m];
    }
}

DevExCode

Master coding interviews with Leetcode, system design, TechBit, QuickLearn, DevTips, Tech Battles, and career services.

© 2026 DevExCode. All rights reserved.