Minimum coins

Dynamic Programming DP on subsequences Hard

Given an integer array of coins representing coins of different denominations and an integer amount representing a total amount of money. Return the fewest number of coins that are needed to make up that amount. If that amount of money cannot be made up by any combination of the coins, return -1. There are infinite numbers of coins of each type

Examples:

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

Output: 3

Explanation: 11 = 5 + 5 + 1. We need 3 coins to make up the amount 11.

Input: coins = [2, 5], amount = 3

Output: -1

Explanation: It's not possible to make amount 3 with coins 2 and 5. Since we can't combine the coin 2 and 5 to make the amount 3, the output is -1.

Input: coins = [1], amount = 0

Constraints

  • n=number of distinct denominations
  • 1 <= n <= 100
  • 1 <= coins[i], amount <= 103

Hints

  • "Define dp[i] as the minimum number of coins needed to make up amount i. the recurrence relation is: dp[i]=min(dp[i],dp[i−coin]+1)for each coin"
  • Since dp[i] only depends on smaller values, we only need a 1D DP array (dp[amount]) instead of O(n × amount).

Company Tags

Ubisoft Wayfair Instacart Mastercard Ernst & Young DoorDash Lyft Texas Instruments Roche Activision Blizzard HCL Technologies Databricks Twilio Rockstar Games Intel McKinsey & Company Dropbox Siemens Healthineers Robinhood Alibaba Bungie Byju's Zynga Zoho Etsy Google Microsoft Amazon Meta Apple Netflix Adobe