Coin Change, a Dynamic Programming problem, by LeetCode

Here it is: https://leetcode.com/problems/coin-change/description/

You are given coins of different denominations and a total amount of money amount. Write a function to compute the fewest number of coins that you need to make up that amount. If that amount of money cannot be made up by any combination of the coins, return -1.
Example 1:
Input: coins = [1, 2, 5], amount = 11
Output: 3 
Explanation: 11 = 5 + 5 + 1
Example 2:
Input: coins = [2], amount = 3
Output: -1
Note:
You may assume that you have an infinite number of each kind of coin.
Same cues again that this is a DP problem: asking for the fewest number of combinations (not the combinations themselves), exponential in nature if you were to compute all permutations. Now it was not said how large "amount" can be, but assume that it is a reasonable value (say <= 1000000). We can find a solution to this problem in O(amount * len(coins))-time and O(amount)-space using DP.
The idea with DP again is to construct the solution from 0,1,2... all the way to amount. Suppose that you're computing the solution for N. And assume that you have 3 coins C1, C2 and C3 (you can generalize later). To get to N, inevitably you'll have to get to either N-C1, or N-C2 or N-C3. Compute the min out of those, add 1. Keep doing that until you reach amount. That's it! Code is below, cheers, Marcelo.


public class Solution
{
 public int CoinChange(int[] coins, int amount)
 {
 //Base
 if (amount < 0) return -1;
 if (amount == 0) return 0;
 //Induction DP
 int[] minChange = new int[amount + 1];
 for (int i = 1; i <= amount; i++)
 {
 int min = Int32.MaxValue;
 for (int j = 0; j < coins.Length; j++)
 if (i - coins[j] >= 0 && minChange[i - coins[j]] != -1 && minChange[i-coins[j]] + 1 < min)
 min = minChange[i - coins[j]] + 1;
 minChange[i] = (min == Int32.MaxValue) ? -1 : min;
 }
 return minChange[amount];
 }
}

Comments

  1. Classics of DP :) My solution is more verbose because it keeps only 2 rows instead of entire matrix in memory, but the idea is the same.

    class Solution {
    public:
    int coinChange(vector& coins, int amount) {
    vector> d(2, vector(amount+1, amount+1));
    d[0][0] = 0;
    bool prev = 0;
    bool current = 1;
    for (int c = 1; c <= coins.size(); ++c) {
    d[current][0] = 0;
    for (long a = 1; a <= amount; ++a) {
    if (coins[c-1] <= a) {
    d[current][a] = min(1 + d[current][a-coins[c-1]], d[prev][a]);
    } else {
    d[current][a] = d[prev][a];
    }
    }
    prev = !prev;
    current = !current;
    }
    auto min_coins = d[prev][amount];
    return min_coins == amount+1 ? -1 : min_coins;
    }
    };

    Reply Delete

Post a Comment

[フレーム]

Popular posts from this blog

Quasi FSM (Finite State Machine) problem + Vibe

Not really an FSM problem since the state isn't changing, it is just defined by the current input. Simply following the instructions should do it. Using VSCode IDE you can also engage the help of Cline or Copilot for a combo of coding and vibe coding, see below screenshot. Cheers, ACC. Process String with Special Operations I - LeetCode You are given a string  s  consisting of lowercase English letters and the special characters:  * ,  # , and  % . Build a new string  result  by processing  s  according to the following rules from left to right: If the letter is a  lowercase  English letter append it to  result . A  '*'   removes  the last character from  result , if it exists. A  '#'   duplicates  the current  result  and  appends  it to itself. A  '%'   reverses  the current  result . Return the final string  result  after processing all char...

Shortest Bridge – A BFS Story (with a Twist)

Here's another one from the Google 30 Days challenge on LeetCode — 934. Shortest Bridge . The goal? Given a 2D binary grid where two islands (groups of 1s) are separated by water (0s), flip the fewest number of 0s to 1s to connect them. Easy to describe. Sneaky to implement well. 🧭 My Approach My solution follows a two-phase Breadth-First Search (BFS) strategy: Find and mark one island : I start by scanning the grid until I find the first 1 , then use BFS to mark all connected land cells as 2 . I store their positions for later use. Bridge-building BFS : For each cell in the marked island, I run a BFS looking for the second island. Each BFS stops as soon as it hits a cell with value 1 . The minimum distance across all these searches gives the shortest bridge. πŸ” Code Snippet Here's the core logic simplified: public int ShortestBridge(int[][] grid) { // 1. Mark one island as '2' and gather its coordinates List<int> island = FindAndMark...

Classic Dynamic Programming IX

A bit of vibe code together with OpenAI O3. I asked O3 to just generate the sieve due to laziness. Sieve is used to calculate the first M primes (when I was using Miller-Rabin, was giving me TLE). The DP follows from that in a straightforward way: calculate the numbers from i..n-1, then n follows by calculating the min over all M primes. Notice that I made use of Goldbach's Conjecture as a way to optimize the code too. Goldbach's Conjecture estates that any even number greater than 2 is the sum of 2 primes. The conjecture is applied in the highlighted line. Cheers, ACC. PS: the prompt for the sieve was the following, again using Open AI O3 Advanced Reasoning: " give me a sieve to find the first M prime numbers in C#. The code should produce a List<int> with the first M primes " Minimum Number of Primes to Sum to Target - LeetCode You are given two integers  n  and  m . You have to select a multiset of  prime numbers  from the  first   m  pri...