Leetcode 1833: Maximum Ice Cream Bars

grid47
grid47
Exploring patterns and algorithms
May 7, 2024 5 min read

A boy wants to buy as many ice cream bars as possible, given their prices and the number of coins he has. Determine the maximum number of ice cream bars he can purchase without exceeding his budget.
Problem
Approach
Steps
Complexity
Input: The input consists of an array `costs` of length `n`, where `costs[i]` is the price of the `i-th` ice cream bar, and an integer `coins` representing the total coins the boy has.
Example: costs = [2, 1, 3, 4, 2], coins = 6
Constraints:
• 1 <= costs.length <= 10^5
• 1 <= costs[i] <= 10^5
• 1 <= coins <= 10^8
Output: Return the maximum number of ice cream bars the boy can buy without exceeding his available coins.
Example: 3
Constraints:
• The output will be a non-negative integer indicating the maximum number of ice cream bars that can be bought.
Goal: Determine the maximum number of ice cream bars the boy can afford given his budget.
Steps:
• Sort the `costs` array in non-decreasing order.
• Iterate through the sorted `costs` array and keep track of the total cost and the number of bars purchased.
• Stop when the total cost exceeds the available `coins`.
Goal: The boy’s budget and the ice cream bar costs are subject to the constraints defined below.
Steps:
• 1 <= costs.length <= 10^5
• 1 <= costs[i] <= 10^5
• 1 <= coins <= 10^8
Assumptions:
• The input array `costs` will contain only valid integer values.
• The `coins` value is guaranteed to be within the specified range.
Input: costs = [2, 1, 3, 4, 2], coins = 6
Explanation: By sorting the costs to [1, 2, 2, 3, 4], the boy can afford 3 ice cream bars for a total of 1 + 2 + 2 = 5 coins, leaving him with enough coins to buy 3 bars.

Input: costs = [5, 3, 8, 2], coins = 4
Explanation: The boy can only afford the ice cream bar with the price of 2 coins. He can buy just one ice cream bar.

Input: costs = [1, 1, 2, 3, 1], coins = 7
Explanation: The boy can afford all 5 bars for a total price of 8 coins, so he can buy 5 ice cream bars.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus