Buy Two Chocolates

You are given an integer array prices representing the prices of various chocolates in a store. You are also given a single integer money, which represents your initial amount of money. You must buy exactly two chocolates in such a way that you still have some non-negative leftover money. You would like to minimize the sum of the prices of the two chocolates you buy. Return the amount of money you will have leftover after buying the two chocolates. If there is no way for you to buy two chocolates without ending up in debt, return money. Note that the leftover must be non-negative.

30:00

Buy Two Chocolates
easy
Free written solution
Topics
Companies

You are given an integer array prices representing the prices of various chocolates in a store. You are also given a single integer money, which represents your initial amount of money. You must buy exactly two chocolates in such a way that you still have some non-negative leftover money. You would like to minimize the sum of the prices of the two chocolates you buy. Return the amount of money you will have leftover after buying the two chocolates. If there is no way for you to buy two chocolates without ending up in debt, return money. Note that the leftover must be non-negative.

Example 1:
Input: {"prices":[1,2,2],"money":3}
Output: 0
Constraints:
  • 2≤prices.length≤502 \leq \text{prices.length} \leq 50

  • 1≤prices[i]≤1001 \leq \text{prices}[i] \leq 100

  • 1≤money≤1001 \leq \text{money} \leq 100

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"prices":[1,2,2],"money":3}

3 chocolate bars and 3 to spend. To keep the most money, buy the two cheapest bars. No sort needed: keep the two smallest prices in one pass.

the shelf

1

2

2

cheapest

∞

empty

+

second cheapest

∞

empty

wallet: 3

pair cost so far: ∞

Variables
VariableValue
first∞
second∞
money3
DepthFunction Call
Stack empty
0/5