Stamp Collection Value - Problem

You are at a post office with a collection of stamps, each with different denominations. You need to make exact postage for a letter.

Given an array stamps where stamps[i] represents the denomination of the i-th stamp, and an array counts where counts[i] represents how many stamps of denomination stamps[i] you have, find the minimum number of stamps needed to make exactly target postage.

If it's impossible to make the exact postage, return -1.

Note: You can use multiple stamps of the same denomination, but cannot exceed the available count for each denomination.

Input & Output

Example 1 — Basic Case
$ Input: stamps = [1,3,4], counts = [1,2,1], target = 11
Output: 3
💡 Note: Use 1 stamp of value 1, 2 stamps of value 3, and 0 stamps of value 4: 1×1 + 2×3 + 0×4 = 1 + 6 + 0 = 7. Wait, that's only 7. Let me recalculate: 1×1 + 2×3 + 1×4 = 1 + 6 + 4 = 11. Total stamps used: 1 + 2 + 1 = 4 stamps. Actually, better solution: 1×3 + 2×4 = 3 + 8 = 11 using 1 + 2 = 3 stamps.
Example 2 — Impossible Case
$ Input: stamps = [2,4], counts = [1,1], target = 3
Output: -1
💡 Note: Cannot make 3 using stamps of value 2 and 4. Any combination gives even numbers: 0, 2, 4, or 6.
Example 3 — Single Stamp Type
$ Input: stamps = [5], counts = [3], target = 10
Output: 2
💡 Note: Use 2 stamps of value 5: 2×5 = 10. Total stamps used: 2.

Constraints

  • 1 ≤ stamps.length ≤ 100
  • 1 ≤ stamps[i] ≤ 1000
  • 1 ≤ counts[i] ≤ 1000
  • 1 ≤ target ≤ 5000

Visualization

Tap to expand
INPUTStamps & Counts1×13×24×1Target Amount11ALGORITHM1Initialize 2D DP table2Fill table: dp[i][j] = min stamps3Try each stamp count combination4Choose minimum stamps neededDP Table Sample:dp[3][11] = 3 stamps1×3 + 2×4 = 11RESULTMinimum Stamps3Solution: 1×3 + 2×4 stampsTotal value: 3 + 8 = 11 ✓Stamps used: 1 + 2 = 3Optimal Solution!Fewest stamps possibleKey Insight:Build solutions for smaller amounts first, then combine optimally - like fillinga piggy bank one amount at a time, always choosing the fewest stamps possible.TutorialsPoint - Stamp Collection Value | Bottom-Up 2D Dynamic Programming
Asked in
Google 15 Amazon 12 Microsoft 8 Apple 6
23.4K Views
Medium Frequency
~25 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen