LeetCode 2838: Maximum Coins Heroes Can Collect Solution

Master LeetCode problem 2838 (Maximum Coins Heroes Can Collect), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

2838. Maximum Coins Heroes Can Collect

Problem Explanation

Explanation:

To solve this problem, we can use dynamic programming. We can define a 2D array dp where dp[i][j] represents the maximum number of coins that heroes can collect when starting from position (i, j).

We can iterate through the grid starting from the bottom right corner. At each position (i, j), the maximum number of coins that can be collected is the maximum of the coins collected from the right neighbor (i, j+1) and the bottom neighbor (i+1, j), plus the coins at the current position.

Finally, the answer will be stored in dp[0][0], which represents the maximum number of coins that can be collected starting from the top left corner.

Time Complexity:

The time complexity of this approach is O(m*n) where m and n are the dimensions of the grid.

Space Complexity:

The space complexity is also O(m*n) for the 2D array dp.

:

Solution Code

class Solution {
    public int maxCoins(int[][] grid) {
        int m = grid.length;
        int n = grid[0].length;
        
        int[][] dp = new int[m][n];
        
        for (int i = m - 1; i >= 0; i--) {
            for (int j = n - 1; j >= 0; j--) {
                if (i == m - 1 && j == n - 1) {
                    dp[i][j] = grid[i][j];
                } else if (i == m - 1) {
                    dp[i][j] = grid[i][j] + dp[i][j + 1];
                } else if (j == n - 1) {
                    dp[i][j] = grid[i][j] + dp[i + 1][j];
                } else {
                    dp[i][j] = grid[i][j] + Math.max(dp[i][j + 1], dp[i + 1][j]);
                }
            }
        }
        
        return dp[0][0];
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 2838 (Maximum Coins Heroes Can Collect)?

This page provides optimized solutions for LeetCode problem 2838 (Maximum Coins Heroes Can Collect) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 2838 (Maximum Coins Heroes Can Collect)?

The time complexity for LeetCode 2838 (Maximum Coins Heroes Can Collect) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 2838 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 2838 in Java, C++, or Python.

Back to LeetCode Solutions