12. Shop in Candy Store
โ GFG solution to the Shop in Candy Store problem: find minimum and maximum cost to buy all candies with free candy offer using greedy approach. ๐
The problem can be found at the following link: ๐ Question Link
๐งฉ Problem Description
In a candy store, there are different types of candies available and prices[i] represent the price of ith types of candies. You are provided with an attractive offer: For every candy you buy from the store, you can get up to k other different candies for free.
Your task is to find the minimum and maximum amount of money needed to buy all the candies.
Note: In both cases, you must take the maximum number of free candies possible during each purchase.
๐ Examples
Example 1
Input: prices[] = [3, 2, 1, 4], k = 2
Output: [3, 7]
Explanation:
- Minimum cost: Buy candy worth 1, get candies worth 3 and 4 for free. Also buy candy worth 2.
Total: 1 + 2 = 3
- Maximum cost: Buy candy worth 4, get candies worth 1 and 2 for free. Also buy candy worth 3.
Total: 3 + 4 = 7Example 2
๐ Constraints
$1 \le \text{prices.size()} \le 10^5$
$0 \le k \le \text{prices.size()}$
$1 \le \text{prices}[i] \le 10^4$
โ
My Approach
The optimal approach uses Greedy Algorithm with Sorting to maximize the benefit from free candies:
Greedy + Sorting Strategy
Sort the Array:
Sort prices in ascending order to enable optimal greedy selection.
Minimum Cost Strategy:
Buy the cheapest candy and get k most expensive remaining candies for free.
Start from index 0 (cheapest), after each purchase, reduce remaining count by k.
Continue until all candies are covered.
Maximum Cost Strategy:
Buy the most expensive candy and get k cheapest remaining candies for free.
Start from last index (most expensive), after each purchase, increase lower bound by k.
Continue until all candies are covered.
Implementation Details:
Use remaining count tracking for minimum cost calculation.
Use index boundary tracking for maximum cost calculation.
๐ Time and Auxiliary Space Complexity
Expected Time Complexity: O(n log n), where n is the size of the prices array. The sorting step dominates the complexity, while the two loops run in O(n) time combined.
Expected Auxiliary Space Complexity: O(1), as we only use a constant amount of additional space for variables like indices, costs, and bounds.
๐งโ๐ป Code (C++)
โ Code (Java)
๐ Code (Python)
๐ง Contribution and Support
For discussions, questions, or doubts related to this solution, feel free to connect on LinkedIn: ๐ฌ Any Questions?. Let's make this learning journey more collaborative!
โญ If you find this helpful, please give this repository a star! โญ
๐Visitor Count
Last updated