2
/** Closest cost result */3
int closestCost = Integer.MAX_VALUE;5
/** Difference between closest cost result and target so far */6
int closestCostDiff = Integer.MAX_VALUE;8
public int closestCost(int[] baseCosts, int[] toppingCosts, int target) {9
for (int base : baseCosts) {10
dfs(toppingCosts, 0, base, target);15
public void dfs(int[] toppingCosts, int toppingIndex, int cost, int target) {16
int costDiff = Math.abs(target - cost);17
if (costDiff < closestCostDiff || (costDiff == closestCostDiff && cost < closestCost)) {18
closestCostDiff = costDiff;22
// Since toppings are all positive cost, stop dfs early if cost exceeds target23
if (toppingIndex >= toppingCosts.length || cost > target) return;25
dfs(toppingCosts, toppingIndex + 1, cost, target);26
dfs(toppingCosts, toppingIndex + 1, cost + toppingCosts[toppingIndex], target);27
dfs(toppingCosts, toppingIndex + 1, cost + 2 * toppingCosts[toppingIndex], target);