NeetCode #762LC-2706EasyGreedy
← Back to All Problems

#762 · #2706 · Buy Two Chocolates(购买两块巧克力)

📌 Problem Statement & Constraints

You are given an integer array prices and an integer money. You must buy exactly two distinct chocolates. Return the money left after the purchase, or money if you cannot afford two. Constraints: 2 <= prices.length <= 50, 1 <= prices[i] <= 100, 0 <= money <= 100.

💡 Core Algorithmic Approaches

  1. To maximise the leftover, minimise the total cost of two distinct chocolates.
  2. The cheapest pair is the two smallest prices, which can be found by sorting.
  3. If their sum exceeds money, you cannot buy two, so return money unchanged.
  4. Sorting is trivial at this input size and keeps the code short.

💻 Benchmark Python3 Implementation

class Solution:
    def buyChoco(self, prices: List[int], money: int) -> int:
        prices.sort()
        cost = prices[0] + prices[1]
        return money - cost if cost <= money else money

⚡ Complexity Deep Dive

⏱️ Time Complexity
O(n log n): the sort dominates.
💾 Space Complexity
O(1) beyond the sort.

⚠️ Interview Pitfalls & Follow-ups

  • Buying the same chocolate twice: the two chocolates must be distinct indices, so use two different positions.
  • Returning a negative leftover: if the pair is unaffordable, return money unchanged.
  • Picking the two largest values: the goal is the minimum cost, not the maximum.
  • Forgetting that exactly two must be bought: you cannot buy just one cheaper chocolate.