File tree Expand file tree Collapse file tree 1 file changed +34
-0
lines changed
25 - Greedy Algorithm Problems/03 - Shop in Candy Store Expand file tree Collapse file tree 1 file changed +34
-0
lines changed Original file line number Diff line number Diff line change 1+ class Solution {
2+ public:
3+ vector<int > candyStore (int candies[], int N, int K) {
4+ // Sort the candies array in ascending order to find minimum cost easily
5+ sort (candies, candies + N);
6+
7+ // Variables for calculating minimum cost
8+ int mini = 0 ; // Stores the minimum cost
9+ int free = N - 1 ; // Points to the most expensive candy available
10+ int buy = 0 ; // Points to the least expensive candy to buy
11+
12+ // Calculate the minimum cost of buying candies
13+ while (buy <= free) {
14+ mini += candies[buy]; // Add the cost of the current candy being bought
15+ buy++; // Move to the next candy to buy
16+ free -= K; // Reduce the free candies available (K candies become free per purchase)
17+ }
18+
19+ // Variables for calculating maximum cost
20+ int maxi = 0 ; // Stores the maximum cost
21+ free = 0 ; // Points to the least expensive candy available
22+ buy = N - 1 ; // Points to the most expensive candy to buy
23+
24+ // Calculate the maximum cost of buying candies
25+ while (buy >= free) {
26+ maxi += candies[buy]; // Add the cost of the current candy being bought
27+ buy--; // Move to the next candy to buy (from most expensive to least expensive)
28+ free += K; // Increase the number of free candies available (from cheapest candies)
29+ }
30+
31+ // Return the minimum and maximum costs as a vector
32+ return {mini, maxi};
33+ }
34+ };
You can’t perform that action at this time.
0 commit comments