Buy Two Chocolates — LeetCode 2706 Python Solution

EasyGreedyArraySorting
Problem
#2706
Pattern
Greedy
Reading time
2 min

The problem

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.

Example

Input
prices = [1,2,2], money = 3
Output
0
Explanation
Purchase the chocolates priced at 1 and 2 units respectively. You will have 3 - 3 = 0 units of money afterwards. Thus, we return 0.

Python solution

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

Complexity

MeasureComplexity
TimeO(n \times \log n)
SpaceO(\log n) auxiliary

Pattern: Greedy

Take the locally best option every time — when you can prove that never costs you later. LeetCode 2706. Buy Two Chocolates is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Greedy.

The greedy guide has the Python template for the pattern and the 346 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 2706. Buy Two Chocolates?
LeetCode 2706. Buy Two Chocolates is rated Easy on LeetCode.
What is the time complexity of LeetCode 2706. Buy Two Chocolates?
The Python solution on this page runs in O(n \times \log n).
What is the space complexity of LeetCode 2706. Buy Two Chocolates?
The Python solution on this page uses O(\log n) auxiliary space.
What topics does LeetCode 2706. Buy Two Chocolates cover?
LeetCode 2706. Buy Two Chocolates is tagged Greedy, Array and Sorting on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview