In LeetCode Store, there are n items to sell. Each item has a price. However, there are some special offers, and a special offer consists of one or more different kinds of items with a sale price.

You are given an integer array price where price[i] is the price of the ith item, and an integer array needs where needs[i] is the number of pieces of the ith item you want to buy.

You are also given an array special where special[i] is of size n + 1 where special[i][j] is the number of pieces of the jth item in the ith offer and special[i][n] (i.e., the last integer in the array) is the price of the ith offer.

Return the lowest price you have to pay for exactly certain items as given, where you could make optimal use of the special offers. You are not allowed to buy more items than you want, even if that would lower the overall price. You could use any of the special offers as many times as you want.

Input & Output

Example 1 — Basic Shopping
$ Input: price = [2,5], special = [[3,0,5],[1,2,10]], needs = [3,2]
Output: 14
💡 Note: Use special offer [3,0,5] to buy 3 items of type 0 for $5, then buy 2 items of type 1 individually for $10. Total: 5 + 10 = 14.
Example 2 — Multiple Offers
$ Input: price = [2,3,4], special = [[1,1,0,4],[2,2,1,9]], needs = [1,2,1]
Output: 11
💡 Note: Use offer [1,1,0,4] once and buy remaining items individually: 4 + 3 + 4 = 11. This is cheaper than individual prices (2+6+4=12) or other combinations.
Example 3 — No Beneficial Offers
$ Input: price = [1,1], special = [[2,2,5]], needs = [2,2]
Output: 4
💡 Note: The special offer costs $5 for [2,2] but buying individually costs only $4 (2×1 + 2×1). Choose individual purchases.

Constraints

  • n == price.length == needs.length
  • 1 ≤ n ≤ 6
  • 0 ≤ price[i], needs[i] ≤ 10
  • 1 ≤ special.length ≤ 100
  • special[i].length == n + 1
  • 0 ≤ special[i][j] ≤ 50

Visualization

Tap to expand
Shopping Offers: Find Minimum CostPrices[2, 5]Special Offers[[3,0,5],[1,2,10]]Needs[3, 2]Individual: 3×2 + 2×5 = 16Offer [3,0,5]: 5 + 2×5 = 15Optimal: 5 + 2×5 = 14Buy all individuallyUse offer [3,0,5]Mixed strategyDecision ProcessTry all offer combinationsCompare with individual pricesMinimum Cost: $14
Understanding the Visualization
1
Input
Items needed: [3,2], prices: [2,5], offers: [[3,0,5],[1,2,10]]
2
Decision Tree
Try different combinations of offers vs individual purchases
3
Optimal Cost
Find minimum: Use offer [3,0,5] + buy 2 type-1 items = 14
Key Takeaway
🎯 Key Insight: Use memoization to cache results for each shopping state and avoid redundant calculations
Asked in
Google 15 Amazon 12 Microsoft 8
28.5K 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