Problem 518

Abstract / Summary

Given coin denominations and an amount, find how many ways to make that amount using the coins.

Note

The full problem description, including helpful examples, can be found on LeetCode.

C++ 0518.cpp

class Solution {
public:
    int change(int amount, vector<int>& coins) {
        vector<int> ways, next;
        ways.resize(amount + 1, 0);
        ways[0] = 1;

        for (auto c : coins)
        {
            next = ways;
            for (int base = 0; base < amount; base++)
            {
                if (ways[base] == 0)
                    continue;

                for (int sum = base + c; sum <= amount; sum += c)
                    next[sum] += ways[base];
            }
            swap(ways, next);
        }

        return ways[amount];
    }
};
24 lines | 592 bytes | submitted August 8, 2023 | GitHub   tab size 4

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 60% (1+ million submissions).

Typical patterns to solve this problem:
  • Array
  • Dynamic Programming
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.

See this dedicated page for more details.
LeetCode profile | GitHub repo

Code Walkthrough

Overview

The presented implementation solves the classic coin-change counting problem: given a target amount and a list of coin denominations, it computes how many distinct combinations of those coins sum to the target. The algorithm builds the solution incrementally, processing each coin type one after another and maintaining a dynamic programming table that records the number of ways to reach every intermediate sum.

Core Logic

Initialization of the DP table

vector<int> ways, next;
ways.resize(amount + 1, 0);
ways[0] = 1;

A one-dimensional vector ways of length amount + 1 is allocated and filled with zeros. The entry for sum zero is set to one, representing the empty combination that yields a total of zero. This base case enables the subsequent accumulation of counts.

Iteration over each coin denomination

for (auto c : coins)
{
    next = ways;
    // inner loops
    swap(ways, next);
}

The outer loop extracts each coin value c from the input vector. For every coin, a copy of the current state (ways) is stored in next. This copy serves as the destination for updated counts while preserving the original values needed for the inner computation. After processing the current coin, the two vectors are swapped, making the freshly computed next the new source for the next iteration.

Propagation of counts for a specific coin

for (int base = 0; base < amount; base++)
{
    if (ways[base] == 0)
        continue;

    for (int sum = base + c; sum <= amount; sum += c)
        next[sum] += ways[base];
}

The inner loops walk through every possible intermediate sum base. If there are no ways to achieve base (ways[base] == 0), the algorithm skips further work for that base, avoiding unnecessary arithmetic. When a valid base is found, a secondary loop adds the current coin repeatedly, generating all reachable sums sum that extend base by multiples of c. For each such sum, the count from ways[base] is added to next[sum], thereby accumulating the number of distinct ways that include the current coin.

Final result extraction

return ways[amount];

After all coin denominations have been processed, the entry ways[amount] holds the total number of combinations that sum exactly to the target amount, which is returned to the caller.

Edge Cases Handled

When the target amount is zero, the initialization ways[0] = 1 ensures the function returns one, reflecting the single valid combination: using no coins. If the coin list is empty, the outer loop never executes; the DP table remains unchanged except for the base case, so the function correctly yields zero for any positive amount and one for amount zero. The inner continue statement protects against attempts to propagate from a base with zero ways, which naturally occurs when certain sums are unreachable with the processed subset of coins. The condition sum <= amount in the innermost loop guarantees that the algorithm never writes beyond the allocated vector bounds, even when a coin value exceeds the remaining amount.

Performance Optimizations

The algorithm reuses two vectors (ways and next) throughout the computation, avoiding repeated allocation of fresh storage for each coin. By copying ways into next once per outer iteration and then swapping the references, the code eliminates the need for element-wise copying after the inner loops complete. The early continue when ways[base] equals zero prevents the inner accumulation loop from executing for unreachable bases, reducing the number of arithmetic operations dramatically when the coin set contains large denominations relative to the target. The step size sum += c in the innermost loop leverages the arithmetic progression of reachable sums for a given coin, ensuring that each reachable sum is visited exactly once per base, which streamlines the update process. Overall, the design balances memory usage and computational effort by maintaining a compact DP table and minimizing redundant work.

written by openai gpt

ELI5 - Simplified Explanation

Imagine having a big pile of snacks you want to share, but you need to give someone exactly the right amount. You have different types of coins, and each type is worth a different number of treats. This code is like a smart little robot helper that figures out all the different ways you could pick your coins to reach that exact total amount.

The robot starts by creating a long line of empty boxes, numbered from zero all the way up to the total number of treats you need. It puts a special marker in the first box to show that there is one way to have zero treats, which is by doing absolutely nothing. Then, the robot looks at each type of coin one by one. For every coin, it thinks about all the ways it already found and tries adding that coin over and over again to see if it can reach new numbers.

Every time the robot decides to use a coin, it counts how many ways it can reach each new total and keeps track of those numbers in a fresh set of boxes. It swaps the old boxes for the new ones, making sure it remembers every possibility it discovered. By the time it looks at every single coin, the box at the very end of the line holds the total count of all the ways to combine those coins to get exactly what you wanted.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 7 | μ = 6.78 | σ = 1.37

Complexity Analysis

Time: polynomial
As a rule of thumb, the maximum input size for one second execution time is
  • factorial: up to 10 elements
  • exponential: up to 20 elements
  • polynomial: a few thousand elements
  • loglinear: up to 100,000 elements
  • linear: a few million elements
  • logarithmic: a billion elements
  • constant: practically unlimited
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
Obviously, I did that after I solved the problem myself.

In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.

And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.

(click on a column header to sort the table)
author
author solutions
www AlgoMonster C++ Python Java TS
WalkCCC C++ Python Java
leetcode.ca C++ Python Go Java TS
LeetcodeHelp C++ Python Java
MemoryLimitExceeded C++ Python
Progiez C++ Python Java
github begeekmyfriend C
BigEggStudy C#
everthis JS
fpdjsns C++
halfrost Go
JoshCrozier JS
keineahnung2345 C++
linouk23 C++
lkwq007 Python
ruoru Rust
shreymehul C#
sonugiri1043 C++
suxrobGM C#
wisdompeak C++
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca C++, Go, Java, Python, TypeScript
LeetcodeHelp C++, Java, Python
MemoryLimitExceeded Python, C++
Progiez C++, Java, Python
begeekmyfriend C
BigEggStudy C#
everthis JavaScript
fpdjsns C++
halfrost Go
JoshCrozier JavaScript
keineahnung2345 C++
linouk23 C++
lkwq007 Python
ruoru Rust
shreymehul C#
sonugiri1043 C++
suxrobGM C#
wisdompeak C++
34 links | 20 authors | 9 languages

Videos

5 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

4 similar problems

Solved On The Same Day

19 easy 42 medium 2 hard
64 solutions   August 8, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • Tech Stack - my development environment and tools
  • AI - how AI helped me create this website (NOT solving the problems)
  • Progress - progression over time
  • Quality - code quality