Closest snack pair to budget

Write codeMedium14 min

Your task

A nutrition app shows snack calories sorted ascending. A user wants to pick two different snacks whose combined calories land as close as possible to their remaining daily budget. Given the sorted list calories (length at least 2) and the budget, return the smallest achievable value of |sum - budget| over all pairs. Use converging pointers, not the O(n²) pair scan. Example: calories = [100, 150, 300, 500], budget = 420 gives 20 (100 + 300 = 400, off by 20; no pair gets closer).

Examples

closest_pair_gap(calories: list[int], budget: int) -> int
Example 1
Inputclosest_pair_gap([100, 150, 300, 500], 420)
Output20