|
| 1 | +/** |
| 2 | + * 638. Shopping Offers |
| 3 | + * https://leetcode.com/problems/shopping-offers/ |
| 4 | + * Difficulty: Medium |
| 5 | + * |
| 6 | + * In LeetCode Store, there are n items to sell. Each item has a price. However, there are |
| 7 | + * some special offers, and a special offer consists of one or more different kinds of items |
| 8 | + * with a sale price. |
| 9 | + * |
| 10 | + * You are given an integer array price where price[i] is the price of the ith item, and an |
| 11 | + * integer array needs where needs[i] is the number of pieces of the ith item you want to buy. |
| 12 | + * |
| 13 | + * You are also given an array special where special[i] is of size n + 1 where special[i][j] |
| 14 | + * is the number of pieces of the jth item in the ith offer and special[i][n] (i.e., the last |
| 15 | + * integer in the array) is the price of the ith offer. |
| 16 | + * |
| 17 | + * Return the lowest price you have to pay for exactly certain items as given, where you could |
| 18 | + * make optimal use of the special offers. You are not allowed to buy more items than you want, |
| 19 | + * even if that would lower the overall price. You could use any of the special offers as many |
| 20 | + * times as you want. |
| 21 | + */ |
| 22 | + |
| 23 | +/** |
| 24 | + * @param {number[]} price |
| 25 | + * @param {number[][]} special |
| 26 | + * @param {number[]} needs |
| 27 | + * @return {number} |
| 28 | + */ |
| 29 | +var shoppingOffers = function(price, special, needs) { |
| 30 | + const map = new Map(); |
| 31 | + return dp(needs); |
| 32 | + |
| 33 | + function dp(input) { |
| 34 | + const key = input.join(','); |
| 35 | + if (map.has(key)) return map.get(key); |
| 36 | + let minCost = input.reduce((sum, need, i) => sum + need * price[i], 0); |
| 37 | + for (const offer of special) { |
| 38 | + const nextNeeds = [...input]; |
| 39 | + let valid = true; |
| 40 | + for (let i = 0; i < price.length; i++) { |
| 41 | + if (nextNeeds[i] < offer[i]) { |
| 42 | + valid = false; |
| 43 | + break; |
| 44 | + } |
| 45 | + nextNeeds[i] -= offer[i]; |
| 46 | + } |
| 47 | + if (valid) { |
| 48 | + minCost = Math.min(minCost, offer[price.length] + dp(nextNeeds)); |
| 49 | + } |
| 50 | + } |
| 51 | + map.set(key, minCost); |
| 52 | + return minCost; |
| 53 | + } |
| 54 | +}; |
0 commit comments