Leetcode 2144. Minimum Cost of Buying Candies With Discount
You are given an integer array cost
where cost[i]
is the cost of the i-th
candy. Return the minimum cost of buying all the candies with a special discount applied: Every time you buy two candies, you get an additional candy for free, but you must pick the least expensive available candy as the free one.
cost
be empty?
To minimize the cost, sort the array in descending order, and always pick the third candy directly as free after every two candies bought. This ensures that we are optimizing the discount usage by giving away the least expensive candies.
cost
array in descending order.total_cost
to 0.total_cost
.total_cost
.Here is the implementation based on the described approach:
#include <iostream>
#include <vector>
#include <algorithm>
int minimumCost(std::vector<int>& cost) {
// Sort the cost in descending order
std::sort(cost.begin(), cost.end(), std::greater<int>());
int totalCost = 0;
// Traverse through the list in steps of 3
for (size_t i = 0; i < cost.size(); i++) {
// Add the cost of the first and second candies
if (i % 3 != 2) {
totalCost += cost[i];
}
// Skip the third candy (i.e., do nothing)
}
return totalCost;
}
// For testing purposes
int main() {
std::vector<int> cost = {6, 5, 7, 9, 2, 2};
std::cout << "Minimum cost: " << minimumCost(cost) << std::endl;
return 0;
}
O(n log n)
where n
is the number of candies.O(n)
to traverse through the array, adjusting the total cost.Overall, the time complexity is dominated by the sorting step, hence O(n log n)
.
This solution is efficient and ensures that we apply the discount rule optimally to minimize the total cost.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?