Skip to content

Comments

FAANMG | DP-1#1983

Open
sandy7907 wants to merge 1 commit intosuper30admin:masterfrom
sandy7907:master
Open

FAANMG | DP-1#1983
sandy7907 wants to merge 1 commit intosuper30admin:masterfrom
sandy7907:master

Conversation

@sandy7907
Copy link

No description provided.

@super30admin
Copy link
Owner

Your solution is well-structured and uses dynamic programming correctly. The recurrence relation is appropriate for the unbounded knapsack nature of the problem. However, there are a few areas for improvement:

  1. Magic Number: Avoid using magic numbers like 99999. Instead, use a value that is derived from the problem constraints. For example, you can initialize the unreachable states to amount + 1 (since the maximum number of coins needed cannot exceed amount). This makes the code more readable and robust.

  2. Space Optimization: The current solution uses O(n * amount) space, which is acceptable given the constraints, but can be optimized to O(amount) by using a 1D DP array. This is a common optimization for the coin change problem and reduces the space complexity without affecting the time complexity.

  3. Edge Case Handling: Although your code handles amount=0 correctly (returning 0), it is good practice to explicitly check for such edge cases at the beginning for clarity.

  4. Variable Naming: While r and c are concise, using more descriptive names like nCoins and nAmount might improve readability.

Here is a revised version of your code with these improvements:

class CoinChange {
    public int coinChange(int[] coins, int amount) {
        if (amount == 0) return 0;
        int n = coins.length;
        int[] dp = new int[amount + 1];
        Arrays.fill(dp, amount + 1);
        dp[0] = 0;
        
        for (int coin : coins) {
            for (int j = coin; j <= amount; j++) {
                dp[j] = Math.min(dp[j], 1 + dp[j - coin]);
            }
        }
        
        return dp[amount] > amount ? -1 : dp[amount];
    }
}

This version uses a 1D array, initializes with amount+1, and iterates over coins and then amounts. Note that the inner loop starts from the coin value to avoid negative indices.

Your current solution is correct and efficient, but with these changes, it becomes more robust and efficient in space.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants