Skip to main content
Back to problems
Leetcode
Easy
Arrays
Greedy
Sorting
Buy Two Chocolates

Choose the two cheapest chocolates you can afford and return the money left over, or keep the original amount if no valid pair exists.

Acceptance 0%
Problem Statement

You are given an array of chocolate prices and an amount of money. You want to buy exactly two different chocolates such that the total cost does not exceed your money.

Return the amount of money left after buying the two chocolates with the smallest possible total price that is still affordable. If no pair of chocolates can be bought, return the original amount of money.

The two chocolates must be distinct items from the array.

Input Format

  • An integer array prices, where prices[i] is the price of the ii-th chocolate.
  • An integer money, the amount you can spend.

Output Format

  • Return the remaining money after buying two distinct chocolates with minimum total cost among all affordable pairs.
  • If no valid pair exists, return money.

Constraints

  • Choose exactly two distinct chocolates.
  • The sum of chosen prices must be less than or equal to money.
  • If multiple pairs are affordable, prefer the one with the smallest total price.
  • If no pair is affordable, return money.
Examples
Sample cases returned by the problem API.

Example 1

Input

prices = [1, 2, 2], money = 3

Output

0

Explanation

The two cheapest chocolates cost 1 and 2, which exactly matches the budget. The remaining money is 0.

Example 2

Input

prices = [3, 2, 3], money = 3

Output

3

Explanation

No pair of chocolates can be bought because the cheapest two cost 2 + 3 = 5, which exceeds the budget.

Show 1 more example

Example 3

Input

prices = [3, 1, 2], money = 6

Output

3

Explanation

Buy the two cheapest chocolates, 1 and 2. The remaining money is 6 - 3 = 3.

Premium problem context

Unlock deeper context for this problem

Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.

Guided hints
Editorial and discussion links
Concept map and variants
Sign in to unlock
Track your progress
Sign in to bookmark this problem, save notes, and manage its revision plan.