Skip to content

Commit c413b74

Browse files
authored
Update 1774-closest-dessert-cost.js
1 parent 7745e06 commit c413b74

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed

1774-closest-dessert-cost.js

+30
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,33 @@
1+
/**
2+
* @param {number[]} baseCosts
3+
* @param {number[]} toppingCosts
4+
* @param {number} target
5+
* @return {number}
6+
*/
7+
const closestCost = function(baseCosts, toppingCosts, target) {
8+
let res = baseCosts[0], n = baseCosts.length, m = toppingCosts.length
9+
const { abs } = Math
10+
for (let i = 0; i < n; i++) {
11+
helper(0, baseCosts[i])
12+
}
13+
return res
14+
function helper(i, cur) {
15+
if(
16+
abs(cur - target) < abs(res - target)
17+
|| (abs(cur - target) === abs(res - target) && cur < res)
18+
) {
19+
res = cur
20+
}
21+
if(i === m || cur > target) return
22+
helper(i + 1, cur)
23+
helper(i + 1, cur + toppingCosts[i])
24+
helper(i + 1, cur + toppingCosts[i] * 2)
25+
}
26+
};
27+
28+
// another
29+
30+
131
/**
232
* @param {number[]} baseCosts
333
* @param {number[]} toppingCosts

0 commit comments

Comments
 (0)