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. In order to get the discount, you will follow these steps:
To minimize the total cost:
cost
array in descending order.Here’s a Python code solution that follows the above strategy:
def minimumCost(cost):
# Sort the list in descending order
cost.sort(reverse=True)
total_cost = 0
n = len(cost)
# Process the candies in chunks of three
for i in range(n):
# Add the cost of the candy if it's not the third one in a group of three
if i % 3 != 2:
total_cost += cost[i]
return total_cost
# Example usage:
print(minimumCost([1, 2, 3])) # Output: 5
print(minimumCost([6, 5, 7, 9, 2, 2])) # Output: 23
print(minimumCost([5, 5])) # Output: 10
n
is the number of candies.Hence, the overall time complexity is (O(n \log n)) due to the sorting step.
This approach ensures that we are minimizing the cost by taking the optimal discount repeatedly.
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?