Skip to content

Commit 9be24c4

Browse files
authored
Create main.cpp
1 parent 200ebbc commit 9be24c4

File tree

1 file changed

+34
-0
lines changed
  • 25 - Greedy Algorithm Problems/03 - Shop in Candy Store

1 file changed

+34
-0
lines changed
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
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+
};

0 commit comments

Comments
 (0)