forked from AnasImloul/Leetcode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathClosest Dessert Cost.java
29 lines (25 loc) · 1.12 KB
/
Closest Dessert Cost.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
class Solution {
/** Closest cost result */
int closestCost = Integer.MAX_VALUE;
/** Difference between closest cost result and target so far */
int closestCostDiff = Integer.MAX_VALUE;
public int closestCost(int[] baseCosts, int[] toppingCosts, int target) {
for (int base : baseCosts) {
dfs(toppingCosts, 0, base, target);
}
return closestCost;
}
public void dfs(int[] toppingCosts, int toppingIndex, int cost, int target) {
int costDiff = Math.abs(target - cost);
if (costDiff < closestCostDiff || (costDiff == closestCostDiff && cost < closestCost)) {
closestCostDiff = costDiff;
closestCost = cost;
}
// Since toppings are all positive cost, stop dfs early if cost exceeds target
if (toppingIndex >= toppingCosts.length || cost > target)
return;
dfs(toppingCosts, toppingIndex + 1, cost, target);
dfs(toppingCosts, toppingIndex + 1, cost + toppingCosts[toppingIndex], target);
dfs(toppingCosts, toppingIndex + 1, cost + 2 * toppingCosts[toppingIndex], target);
}
}