Skip to content

Commit 5054273

Browse files
committed
Add solution #638
1 parent 8f3f7c5 commit 5054273

File tree

2 files changed

+55
-0
lines changed

2 files changed

+55
-0
lines changed

README.md

+1
Original file line numberDiff line numberDiff line change
@@ -480,6 +480,7 @@
480480
633|[Sum of Square Numbers](./0633-sum-of-square-numbers.js)|Medium|
481481
636|[Exclusive Time of Functions](./0636-exclusive-time-of-functions.js)|Medium|
482482
637|[Average of Levels in Binary Tree](./0637-average-of-levels-in-binary-tree.js)|Easy|
483+
638|[Shopping Offers](./0638-shopping-offers.js)|Medium|
483484
643|[Maximum Average Subarray I](./0643-maximum-average-subarray-i.js)|Easy|
484485
645|[Set Mismatch](./0645-set-mismatch.js)|Medium|
485486
648|[Replace Words](./0648-replace-words.js)|Medium|

solutions/0638-shopping-offers.js

+54
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
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

Comments
 (0)