All problems
MediumDp

Coin Change

amazongooglemetamicrosoftgoldman-sachs

You are given an integer array coins representing coins of different denominations and an integer amount representing a total amount of money.

Return 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.

You may assume that you have an infinite number of each kind of coin.

Example 1:

Input: coins = [1,5,10,25], amount = 36
Output: 3
Explanation: 25 + 10 + 1 = 36 (3 coins)

Example 2:

Input: coins = [2], amount = 3
Output: -1
Explanation: It is impossible to make 3 using only coins of value 2.

Example 3:

Input: coins = [1,2,5], amount = 11
Output: 3
Explanation: 5 + 5 + 1 = 11 (3 coins)

Examples

Example 1

Input: coins = [1,2,5], amount = 11

Output: 3

Explanation: 11 = 5 + 5 + 1. Three coins is the minimum. Other combos like 2+2+2+2+2+1 use 6 coins.

Example 2

Input: coins = [2], amount = 3

Output: -1

Explanation: No combination of coins with denomination 2 can sum to 3 (an odd number). Return -1.

Constraints

  • -1 <= coins.length <= 12
  • -1 <= coins[i] <= 2^31 - 1
  • -0 <= amount <= 10^4

Optimal Complexity

Time

O(amount * n)

Space

O(amount)

Practice this problem with an AI interviewer

TechInView conducts a full voice mock interview — the AI asks clarifying questions, evaluates your approach, watches you code, and scores you on 5 dimensions. Just like a real FAANG interview.

Start a free interview