Maximum Ice Cream Bars

Updated on 06 June, 2025
Maximum Ice Cream Bars header image

Problem Statement

On a hot summer day, a boy is at a store aiming to purchase some ice cream bars. He has a certain amount of coins, and his objective is to maximize the number of ice cream bars he can buy with these coins. The store has n different ice cream bars, each with a specific cost presented in an array costs of length n, where costs[i] represents the cost of the ith ice cream bar. The boy is free to purchase the ice cream bars in any order he prefers.

The task is to determine the maximum number of ice cream bars the boy can purchase without exceeding the amount of coins he possesses.

Examples

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, and 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 <= 10^5
  • 1 <= costs[i] <= 10^5
  • 1 <= coins <= 10^8

Approach and Intuition

The problem revolves around maximizing the number of ice cream bars a boy can purchase with his available coins. Here's a structured approach leveraging the counting sort mechanism:

  1. Sort the Costs: Sort the array costs in non-decreasing order to prioritize purchasing cheaper bars first.

  2. Initialize Counters: Set up a counter for the number of ice cream bars purchased and a running total for the coins used.

  3. Iterate Over Sorted Costs:

    • For each cost, check if the boy still has enough coins.
    • If yes, subtract the cost from coins and increment the counter.
    • If not, stop the iteration.
  4. Return the Count: The counter now holds the maximum number of ice cream bars the boy can buy.

This greedy approach ensures optimal use of the budget by always choosing the cheapest remaining item, making it efficient and well-suited for the problem’s constraints.

Solutions

  • C++
  • Java
  • JavaScript
  • Python
cpp
class Solution {
public:
    int maximumIceCream(vector<int>& prices, int budget) {
        int countPrices = prices.size();
        int maxPrice = *max_element(prices.begin(), prices.end());
        int totalIceCreams = 0;

        vector<int> priceFrequency(maxPrice + 1);
        for (auto& price : prices) {
            priceFrequency[price]++;
        }

        for (int price = 1; price <= maxPrice; ++price) {
            if (priceFrequency[price] == 0) continue;
            if (budget < price) break;
            
            int maxPossible = min(priceFrequency[price], budget / price);
            budget -= price * maxPossible;
            totalIceCreams += maxPossible;
        }

        return totalIceCreams;
    }
};

This C++ solution helps find the maximum number of ice cream bars that can be purchased given a list of prices and a budget. Here's how the function works:

  • First, it calculates the total number of different prices and identifies the highest price from the list.

  • An integer vector priceFrequency is initialized to keep track of frequency of each price.

  • Loop through each ice cream price to populate the priceFrequency array where the index corresponds to the price and the value at that index represents how many times that price appears.

  • Iterate through possible prices starting from the lowest. For each price:

    • Skip the iteration if the particular price has never occurred (priceFrequency[price] == 0).

    • Stop the loop if the current price exceeds the remaining budget.

    • Calculate the maximum number of bars that can be bought at the current price without exceeding the budget. Update the total ice cream count and decrease the budget accordingly.

  • Return the total number of ice cream bars that can be bought with the provided budget.

In this approach, the solution effectively uses a counting sort mechanism by leveraging the priceFrequency array, which makes it efficient for a range of scenarios, especially when the maximum price is not too large.

java
class Solution {
    public int maxIceCream(int[] prices, int budget) {
        int len = prices.length;
        int totalIceCreams = 0;

        int maxCost = prices[0];
        for (int price : prices) {
            maxCost = Math.max(maxCost, price);
        }

        int[] frequency = new int[maxCost + 1];
        for (int price : prices) {
            frequency[price]++;
        }

        for (int price = 1; price <= maxCost; ++price) {
            if (frequency[price] == 0) continue;
            if (budget < price) break;

            int canBuy = Math.min(frequency[price], budget / price);
            budget -= price * canBuy;
            totalIceCreams += canBuy;
        }

        return totalIceCreams;
    }
}

The provided solution in Java resolves the problem of finding out the maximum number of ice cream bars that can be purchased with a given budget. The algorithm makes use of a frequency array to facilitate an efficient computation of how many ice creams can be purchased without exceeding the budget.

Here's a step-by-step breakdown of the solution:

  1. Retrieve the length of the prices array and initialize variables for keeping track of the total number of ice creams (totalIceCreams) that can be bought, and a variable maxCost to store the maximum price of an ice cream.
  2. Iterate over the prices array to find the maximum price (maxCost).
  3. Create and fill a frequency array where each index represents a price and the value at that index represents the frequency of that price in the prices array.
  4. Iterate through the frequency array starting from the lowest price. For each price:
    • Continue to next price if no ice cream is available at the current price.
    • Break the loop if the current price exceeds the remaining budget.
    • Calculate the maximum number of ice creams that can be bought at the current price without exceeding the budget (canBuy).
    • Subtract the total cost of these ice creams from the budget.
    • Increment the count of total ice creams purchased (totalIceCreams) by the number of ice creams bought at the current price.
  5. Return the total number of ice creams that can be bought.

This approach is efficient as it reduces the need to sort the prices array and instead uses the price-based frequency count to directly compute the possible purchases, leveraging the budget constraints optimally.

js
var countMaxIceCreams = function(prices, budget) {
    let length = prices.length;
    let totalIceCreams = 0;
    let maxPrice = Math.max(...prices);

    let priceHistogram = Array(maxPrice + 1).fill(0);
    for (let price of prices) {
        priceHistogram[price] += 1;
    }

    for (let price = 1; price <= maxPrice; ++price) {
        if (!priceHistogram[price]) {
            continue;
        }
        if (budget < price) {
            break;
        }

        let possibleCount = Math.min(priceHistogram[price], Math.floor(budget / price));
        budget -= price * possibleCount;
        totalIceCreams += possibleCount;
    }

    return totalIceCreams;
};

The JavaScript function countMaxIceCreams calculates the maximum number of ice cream bars you can buy given a list of prices and a total budget. Aim to understand how the function leverages an efficient strategy to derive the maximum ice cream count.

  • Begin by establishing variables for tracking the length of the price array, the cumulative number of ice creams bought, and the maximum price from the price list.
  • Construct a histogram (priceHistogram) from the price array. This histogram details the frequency of each ice cream price up to the maximum price.
  • Iterate through each possible price, leveraging the histogram. Disregard prices that are not in the histogram (frequency is zero).
  • Verify if the current budget is less than the price being considered; break the loop if true as further purchases are not possible.
  • Calculate the maximum number of ice creams that can be bought at the current price without exceeding the budget, then adjust the budget accordingly.
  • Sum up the count of ice creams bought at each price level to get the total count of affordable ice creams within the given budget.

By employing a histogram for frequency counting and working directly with various price levels, the function efficiently computes the result without directly sorting the price list, thus optimizing the process.

python
class Solution:
    def maximumIceCreams(self, costs: List[int], budget: int) -> int:
        totalIceCreams, length = 0, len(costs)
        maxCost = max(costs)

        priceFrequency = [0] * (maxCost + 1)
        for price in costs:
            priceFrequency[price] += 1

        for price in range(1, maxCost + 1):
            if priceFrequency[price] == 0:
                continue
            if budget < price:
                break

            maxAffordable = min(priceFrequency[price], budget // price)
            budget -= price * maxAffordable
            totalIceCreams += maxAffordable

        return totalIceCreams

This Python solution tackles the problem of determining the maximum number of ice cream bars that can be purchased given a list of costs and a budget. The strategy used involves counting frequencies of each price to efficiently calculate the maximum number of ice creams that fit within the budget. Below is a breakdown of the implementation steps:

  1. Initialize totalIceCreams to count the number of ice creams bought, and compute the length of costs list and the maxCost for optimization.

  2. Set up a priceFrequency list to keep the frequency of each ice cream price. This list is initialized to zeros, with its length set to maxCost + 1 to cover all possible prices counted from 0.

  3. Populate the priceFrequency array where each index represents the price of an ice cream and the value at that index represents how many times that price appears in the input list.

  4. Loop through each possible price from 1 to maxCost. Skip the current price if its frequency is zero. If the remaining budget is less than the current price, exit the loop as no more ice creams can be bought.

  5. Determine maxAffordable, the maximum number of ice creams that can be bought at the current price without exceeding the budget. This involves taking the minimum of the count of that price and the maximum number the budget can accommodate (budget // price).

  6. Adjust the budget by subtracting the total cost of the maxAffordable ice creams at the current price.

  7. Increase totalIceCreams by maxAffordable.

The function finally returns totalIceCreams, which represents the maximum number of ice cream bars that can be bought within the given budget. This method ensures an efficient use of the budget by prioritizing the purchase of cheaper ice creams first and using frequency counts to skip unnecessary price checks.

Comments

No comments yet.