Uber · Question 65 · Dynamic Programming
Coin Change (Unbounded Knapsack)
Problem
Given coins of various denominations and a total amount, return the fewest coins needed to make that amount. Return - 1 if not possible.
Approach
1D DP: For each coin, update dp[amount] = min(dp[amount], dp[amount - coin] + 1)
Time O(amount×len(coins))Space O(amount)
How it works
- 1dp[a] = fewest coins for amount a.
- 2Each coin relaxes all reachable amounts.
- 3Unreachable stays infinite -> return -1.
Sample input / output
Input: 3 11 1 2 5 Output: 3
Constraints
1 <= coins.length <= 12; 1 <= coins[i] <= 2^31-1; 0 <= amount <= 10^4.
Solution — read it, then walk it
Time O(amount×len(coins))Space O(amount)Loops 2Branches 1Returns 1source · Python
Scroll sideways for wide charts — the view follows the active step.
- start / end
- statement
- condition
- loop
- returns
- definition
1/17
StartSTART
Interactive control-flow diagram and step-by-step code walkthrough.
Recommended resourcesAffiliate links · may earn us a commission
Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Cloud hosting for side projectsShip the portfolio project that gets you hired — free credits for new accounts.Claim credits