Minimum Cost of Buying Candies With Discount - Problem

๐Ÿฌ Welcome to the Sweet Candy Shop! This shop has an amazing deal that will make any candy lover excited.

The Deal: For every two candies you buy, you get a third candy absolutely free! But there's a catch - the free candy must cost less than or equal to the cheaper of the two candies you purchased.

Your Mission: Given an array cost where cost[i] represents the price of the i-th candy, find the minimum total cost to buy all candies using this discount optimally.

Example Strategy: If candies cost [1, 2, 3, 4] and you buy candies costing 2 and 3, you can take the candy costing 1 for free (since 1 โ‰ค min(2,3) = 2), but not the candy costing 4.

Goal: Return the minimum cost to purchase all candies by strategically using the buy-2-get-1-free discount.

Input & Output

example_1.py โ€” Basic case with perfect groups
$ Input: cost = [1, 2, 3]
โ€บ Output: 5
๐Ÿ’ก Note: Buy candies with costs 2 and 3, get candy with cost 1 free. Total cost = 2 + 3 = 5.
example_2.py โ€” Mixed grouping required
$ Input: cost = [6, 5, 7, 9, 2, 2]
โ€บ Output: 23
๐Ÿ’ก Note: Sort: [9,7,6,5,2,2]. Group 1: buy 9+7, get 6 free (cost=16). Group 2: buy 5+2, get 2 free (cost=7). Total = 16 + 7 = 23.
example_3.py โ€” Edge case with remainder
$ Input: cost = [5, 5]
โ€บ Output: 10
๐Ÿ’ก Note: Only 2 candies, cannot form a group of 3. Must buy both candies at full price. Total = 5 + 5 = 10.

Constraints

  • 1 โ‰ค cost.length โ‰ค 1000
  • 1 โ‰ค cost[i] โ‰ค 100
  • All candy costs are positive integers

Visualization

Tap to expand
๐Ÿฌ Smart Candy Shopping StrategyCandy Store: Buy 2 Get 1 FREE!(Free candy must cost โ‰ค min price of bought candies)Available: $6, $5, $7, $9, $2, $2Step 1: Sort by Price (Descending)$9$7$6$5$2$2Step 2: Form Optimal GroupsGroup 1$9BUY$7BUY$6FREEGroup 2$5BUY$2BUY$2FREEFinal CalculationGroup 1: $9 + $7 = $16Group 2: $5 + $2 = $7Total: $23Saved: $6 + $2 = $8 compared to buying all!
Understanding the Visualization
1
Survey the Store
Look at all candy prices and arrange them from most to least expensive
2
Strategic Grouping
Group candies in sets of 3, always putting the most expensive ones first
3
Apply the Deal
For each group of 3, buy the 2 most expensive and get the cheapest one free
4
Final Purchase
Buy any remaining 1-2 candies at full price
Key Takeaway
๐ŸŽฏ Key Insight: By sorting candies in descending order and using a greedy approach, we maximize our savings by always getting the most expensive possible candies for free while respecting the discount rules.
Asked in
Amazon 45 Google 32 Microsoft 28 Meta 15
42.0K Views
Medium Frequency
~15 min Avg. Time
1.9K Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen