Skip to the code
cf.
+25 XP

#116 Closest Three-Item Bundle

medium

A gift shop suggests a bundle of three different products whose total price is as close as possible to the customer's budget. Prices are in prices, in no particular order.

Write closestBundle(prices, budget) that returns the total price of three products (three different indexes) whose total is closest to budget. If two totals are equally close, return the smaller total.

Example 1

Input: prices = [12,4,30,9,18], budget = 40
Output: 39

12 + 9 + 18 = 39 is 1 away. No total of three products is exactly 40.

Example 2

Input: prices = [5,5,5], budget = 20
Output: 15

Only one bundle is possible.

Constraints

  • 3 <= prices.length <= 1000
  • 1 <= prices[i] <= 10^4
  • 1 <= budget <= 3 * 10^4
Saved in this browser

Run tries your code on the examples. Submit runs every test, including hidden edge cases, and solves the problem when they all pass.

Ctrl + Enter runs, Ctrl + Shift + Enter submits (⌘ on a Mac).