Maximum Ice Cream Bars Solution in Java

Ah, the age-old dilemma: you have a pocket full of coins, and all you want is to indulge in some delicious ice cream bars. But wait! The ice cream vendor has a price list that seems to mock your financial situation. Welcome to the Maximum Ice Cream Bars problem, where you must navigate the treacherous waters of budgeting while trying to satisfy your sweet tooth.

Imagine this: you walk up to the ice cream truck, and the vendor greets you with a smile, but as you glance at the prices, you realize you can only afford a few bars. It’s like being at a buffet but only having enough money for a single plate of salad. The struggle is real!

Solution Links


Problem Description

In this problem, you are given an array of integers representing the costs of ice cream bars and an integer representing the total amount of coins you have. Your task is to determine the maximum number of ice cream bars you can buy without exceeding your budget.

Code Solution


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;
  }
}

Approach Explanation

The approach taken in this solution is straightforward yet effective. First, we sort the array of costs. This allows us to start purchasing the cheapest ice cream bars first, maximizing the number we can buy. We then iterate through the sorted costs, deducting the cost of each bar from our total coins until we can no longer afford the next one. If we can’t afford a bar, we return the count of bars we have successfully purchased.

Time and Space Complexity

  • Time Complexity: O(n log n) due to the sorting of the costs array, where n is the number of ice cream bars.
  • Space Complexity: O(1) since we are using a constant amount of space for our variables.

Real-World Example

Picture this: you’re at a summer fair, and the ice cream stand is calling your name. You have $10, and the prices are $1, $2, $3, and $5 for the bars. You start with the $1 bar, then the $2, and so on. By the time you reach the $5 bar, you realize you can only afford two more bars. You walk away with a smile, ice cream in hand, and a story to tell about how you maximized your ice cream intake without breaking the bank!

Similar Problems

  • 2 Sum Solution in Java