LeetCode Solution: Maximum Ice Cream Bars question

Question: 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. 

Return the maximum number of ice cream bars the boy can buy with coins coins.

Note: The boy can buy the ice cream bars in any order.


Solution: This solution first sorts the costs array in ascending order, and then iterates through the costs array. For each cost, it checks if the cost is less than or equal to the available coins. If it is, it adds one to the maximum number of ice cream bars and subtracts the cost from the available coins. If the cost is greater than the available coins, the loop is broken and the maximum number of ice cream bars is returned.

public class IceCreamBars {

    public int maximumIceCreamBars(int[] costs, int coins) {

        // Sort the costs array in ascending order

        Arrays.sort(costs);

        

        // Initialize the maximum number of ice cream bars to 0

        int maxIceCreamBars = 0;

        

        // Iterate through the costs array

        for (int cost : costs) {

            // If the current cost is greater than the available coins, break the loop

            if (cost > coins) {

                break;

            }

            // Otherwise, add one to the maximum number of ice cream bars and subtract the cost from the available coins

            maxIceCreamBars++;

            coins -= cost;

        }

        

        return maxIceCreamBars;

    }

}


No comments:

Post a Comment