Skip to main content
Back to problems
#2706
Easy Algorithms

Buy two chocolates

Array Greedy Sorting
68.3% acceptance
Feb 25, 2026
1067
72
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.

Solution

Rust
Time O(n log n)
Space O(1)
LeetCode
solution.rs
impl Solution {
  pub fn buy_choco(prices: Vec<i32>, money: i32) -> i32 {
    let mut p = prices;
    p.sort();
    let min_sum = p[0] + p[1];
    if min_sum <= money { money - min_sum } else { money }
  }
}