Maximum Ice Cream Bars — LeetCode 1833 Python Solution

MediumGreedyArrayCounting SortSorting
Problem
#1833
Pattern
Greedy
Reading time
2 min

The problem

It is a sweltering summer day, and a boy wants to buy some ice cream bars. At the store, there are n ice cream bars.

Example

Input
costs = [1,3,2,4,1], coins = 7
Output
4
Explanation
The boy can buy ice cream bars at indices 0,1,2,4 for a total price of 1 + 3 + 2 + 1 = 7.

Python solution

Python
class Solution:
    def maxIceCream(self, costs: List[int], coins: int) -> int:
        costs.sort()
        for i, c in enumerate(costs):
            if coins < c:
                return i
            coins -= c
        return len(costs)

Complexity

MeasureComplexity
TimeO(n \times \log n)
SpaceO(\log n), where n is the length of the costs array auxiliary

Pattern: Greedy

Take the locally best option every time — when you can prove that never costs you later. LeetCode 1833. Maximum Ice Cream Bars 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 1833. Maximum Ice Cream Bars?
LeetCode 1833. Maximum Ice Cream Bars is rated Medium on LeetCode.
What is the time complexity of LeetCode 1833. Maximum Ice Cream Bars?
The Python solution on this page runs in O(n \times \log n).
What is the space complexity of LeetCode 1833. Maximum Ice Cream Bars?
The Python solution on this page uses O(\log n), where n is the length of the costs array auxiliary space.
What topics does LeetCode 1833. Maximum Ice Cream Bars cover?
LeetCode 1833. Maximum Ice Cream Bars is tagged Greedy, Array, Counting Sort 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