Skip to content

Commit 6726799

Browse files
authored
Update 638-shopping-offers.js
1 parent 8ee2cfe commit 6726799

File tree

1 file changed

+43
-0
lines changed

1 file changed

+43
-0
lines changed

638-shopping-offers.js

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,46 @@
1+
/**
2+
* @param {number[]} price
3+
* @param {number[][]} special
4+
* @param {number[]} needs
5+
* @return {number}
6+
*/
7+
const shoppingOffers = function (price, special, needs) {
8+
return helper(price, special, needs, 0);
9+
}
10+
11+
12+
function helper(price, special, needs, pos) {
13+
let local_min = directPurchase(price, needs);
14+
for (let i = pos; i < special.length; i++) {
15+
let offer = special[i];
16+
let temp = [];
17+
for (let j = 0; j < needs.length; j++) {
18+
if (needs[j] < offer[j]) { // check if the current offer is valid
19+
temp = null;
20+
break;
21+
}
22+
temp.push(needs[j] - offer[j]);
23+
}
24+
25+
if (temp !== null) { // use the current offer and try next
26+
local_min = Math.min(local_min, offer[offer.length - 1] + helper(price, special, temp, i));
27+
}
28+
}
29+
30+
return local_min;
31+
}
32+
33+
function directPurchase(price, needs) {
34+
let total = 0;
35+
for (let i = 0; i < needs.length; i++) {
36+
total += price[i] * needs[i];
37+
}
38+
39+
return total;
40+
}
41+
42+
// another
43+
144
/**
245
* @param {number[]} price
346
* @param {number[][]} special

0 commit comments

Comments
 (0)