← Uber bank

Uber · Question 65 · Dynamic Programming

Coin Change (Unbounded Knapsack)

Dynamic ProgrammingPythoncode⏱ O(amount×len(coins))💾 O(amount)
Product-based

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

  1. 1dp[a] = fewest coins for amount a.
  2. 2Each coin relaxes all reachable amounts.
  3. 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.
↻ repeat↻ repeatyesnoSTARTcoins, amountMAX = float('inf')dp = [0] + [MAX] * amountfor coin in coinsfor a in range(coin,amount + 1)dp[a] = min(dp[a], dp[a -coin] + 1)RETURN dp[amount] ifdp[amount] != MAX else -1DEFINE main()import sysdata =sys.stdin.read().split()it = iter(data)n = int(next(it)); amount =int(next(it))coins = [int(next(it)) for_ in range(n)]print(coinChange(coins,amount))if __name__ =="__main__"main()END
  • 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