1833. Maximum Ice Cream Bars LeetCode Solution
In this guide, you will get 1833. Maximum Ice Cream Bars LeetCode Solution with the best time and space complexity. The solution to Maximum Ice Cream Bars problem is provided in various programming languages like C++, Java, and Python. This will be helpful for you if you are preparing for placements, hackathons, interviews, or practice purposes. The solutions provided here are very easy to follow and include detailed explanations.
Table of Contents
- Problem Statement
- Complexity Analysis
- Maximum Ice Cream Bars solution in C++
- Maximum Ice Cream Bars solution in Java
- Maximum Ice Cream Bars solution in Python
- Additional Resources

Problem Statement of Maximum Ice Cream Bars
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. You are given an array costs of length n, where costs[i] is the price of the ith ice cream bar in coins. The boy initially has coins coins to spend, and he wants to buy as many ice cream bars as possible.
Note: The boy can buy the ice cream bars in any order.
Return the maximum number of ice cream bars the boy can buy with coins coins.
You must solve the problem by counting sort.
Example 1:
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.
Example 2:
Input: costs = [10,6,8,7,7,8], coins = 5
Output: 0
Explanation: The boy cannot afford any of the ice cream bars.
Example 3:
Input: costs = [1,6,3,1,2,5], coins = 20
Output: 6
Explanation: The boy can buy all the ice cream bars for a total price of 1 + 6 + 3 + 1 + 2 + 5 = 18.
Constraints:
costs.length == n
1 <= n <= 105
1 <= costs[i] <= 105
1 <= coins <= 108
Complexity Analysis
- Time Complexity: O(\texttt{sort})
- Space Complexity: O(\texttt{sort})
1833. Maximum Ice Cream Bars LeetCode Solution in C++
class Solution {
public:
int maxIceCream(vector<int>& costs, int coins) {
ranges::sort(costs);
for (int i = 0; i < costs.size(); ++i)
if (coins >= costs[i])
coins -= costs[i];
else
return i;
return costs.size();
}
};
/* code provided by PROGIEZ */
1833. Maximum Ice Cream Bars LeetCode Solution in Java
class Solution {
public int maxIceCream(int[] costs, int coins) {
Arrays.sort(costs);
for (int i = 0; i < costs.length; ++i)
if (coins >= costs[i])
coins -= costs[i];
else
return i;
return costs.length;
}
}
// code provided by PROGIEZ
1833. Maximum Ice Cream Bars LeetCode Solution in Python
class Solution:
def maxIceCream(self, costs: list[int], coins: int) -> int:
for i, cost in enumerate(sorted(costs)):
if coins >= cost:
coins -= cost
else:
return i
return len(costs)
# code by PROGIEZ
Additional Resources
- Explore all LeetCode problem solutions at Progiez here
- Explore all problems on LeetCode website here
Happy Coding! Keep following PROGIEZ for more updates and solutions.