# LeetCode: Closest Dessert Cost Solution

## Approach

Exhausive search through all possibilities of topping

(0, 1, 2)
for each

## Implementation

```.css-ds3kc{display:table-row;}.css-1t8atru{display:table-cell;opacity:0.5;padding-right:var(--chakra-space-6);-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none;text-align:right;}1.css-2qghsv{display:table-cell;}function recursion(cost, toppingCosts, toppingCostsIdx, target, ref) {2  if (toppingCostsIdx === toppingCosts.length) {3    const diff = Math.abs(target - cost)4    if (diff <= ref.minDiff) {5      ref.cost = diff === ref.minDiff ? Math.min(ref.cost, cost) : cost6      ref.minDiff = diff7    }8  } else {9    recursion(10      cost + toppingCosts[toppingCostsIdx] * 0,11      toppingCosts,12      toppingCostsIdx + 1,13      target,14      ref15    )16    recursion(17      cost + toppingCosts[toppingCostsIdx] * 1,18      toppingCosts,19      toppingCostsIdx + 1,20      target,21      ref22    )23    recursion(24      cost + toppingCosts[toppingCostsIdx] * 2,25      toppingCosts,26      toppingCostsIdx + 1,27      target,28      ref29    )30  }31}32
33/**34 * @param {number[]} baseCosts35 * @param {number[]} toppingCosts36 * @param {number} target37 * @return {number}38 */39var closestCost = function (baseCosts, toppingCosts, target) {40  const ref = { minDiff: Infinity, cost: Infinity }41  for (const baseCost of baseCosts) {42    recursion(baseCost, toppingCosts, 0, target, ref)43  }44  return ref.cost45}```

leetcode

recursion

greedy

## Next Post

LeetCode: Count Items Matching A Rule

Feb 28, 2021

Search Posts