Sponsored
Sponsored
This approach involves sorting the array of costs to ensure the boy buys the cheapest available ice cream bars first. After sorting, iterate through the list and keep buying bars until you run out of coins.
Steps involve:
Time Complexity: O(n log n) due to the sorting step.
Space Complexity: O(1), as no additional space is required beyond the input.
1#include <stdio.h>
2#include <stdlib.h>
3
4int compare(const void *a, const void *b) {
5 return *(int *)a - *(int *)b;
6}
7
8int maxIceCream(int* costs, int costsSize, int coins) {
9 qsort(costs, costsSize, sizeof(int), compare);
10 int count = 0;
11 for (int i = 0; i < costsSize; i++) {
12 if (coins >= costs[i]) {
13 coins -= costs[i];
14 count++;
15 } else {
16 break;
17 }
18 }
19 return count;
20}
21
22int main() {
23 int costs[] = {1, 3, 2, 4, 1};
24 int coins = 7;
25 printf("%d\n", maxIceCream(costs, 5, coins));
26 return 0;
27}
This C program sorts the costs array using qsort and calculates the maximum number of ice creams that can be bought while iterating through the sorted array. It returns the count of ice creams the boy can afford.
This solution uses a variation of counting sort suitable for this specific problem due to the constraint that costs[i] <= 100,000.
Steps involve:
Time Complexity: O(n + max(costs)), where max(costs) could be up to 100,000.
Space Complexity: O(max(costs)), because of the frequency array used.
1def maxIceCream(costs, coins):
2 max_cost = max(costs)
This Python solution uses a frequency array to store the number of each cost. By iterating over these costs in order (with known max cost), it calculates how many bars of each cost can be purchased and subtracts the respective cost from the available coins, tallying the total ice creams bought.