Find the minimum and maximum amount to buy all N candies
Pattern: Candy and assign cookies
Each time you buy a candy you also take up to k others free, so you pay for exactly ceil(n / (k + 1)) candies. For the least spend, pay for the cheapest ones and take the dearest free; for the most, pay for the dearest and take the cheapest free.
No verified practice link yet. The guide below states the problem in full, so you can still solve it here.
The problem
A shop sells n candies. Every time you buy one, you must also take up to k others for free (fewer only when fewer
are left). Return [least, most] that buying all the candies can cost. [3, 2, 1, 4] with k = 2 gives [3, 7].
The catalogue has no practice link for this one.
Think first
- How many candies do you pay for, whatever you choose?
- For the least cost, which ones?
- And for the most?
Hints
Brute force, and why it fails
Try every set of paid candies of that size: exponential.
The key insight
The number of paid candies is fixed, and any set of that size can be the paid set, so the answer is the sum of the cheapest or dearest that many.
Dry run
| paid | 2 |
|---|
Prices [3, 2, 1, 4], k = 2. Sorted 1, 2, 3, 4. You pay for ceil(4 / 3) = 2 candies.
The plan
sort prices; paid = (n + k) / (k + 1)
min = sum of the first paid; max = sum of the last paid
Complexity
- Time
O(n log n)- Space
O(n)
Sorting dominates.
Edge cases
- k = 0: you pay for everything.
- k at least n - 1: you pay for one.
- One candy.
I've built my logic, show the code
Java
import java.util.*;
class Solution {
public int[] candyStore(int[] candies, int k) {
int[] c = candies.clone();
Arrays.sort(c);
int n = c.length, paid = (n + k) / (k + 1); // each bought candy brings k free ones
int min = 0, max = 0;
for (int i = 0; i < paid; i++) {
min += c[i]; // pay for the cheapest, take the dearest free
max += c[n - 1 - i]; // pay for the dearest, take the cheapest free
}
return new int[]{min, max};
}
}C++
class Solution {
public:
vector<int> candyStore(vector<int>& candies, int k) {
vector<int> c(candies);
sort(c.begin(), c.end());
int n = static_cast<int>(c.size()), paid = (n + k) / (k + 1); // each bought candy brings k free ones
int mn = 0, mx = 0;
for (int i = 0; i < paid; i++) {
mn += c[i]; // pay for the cheapest, take the dearest free
mx += c[n - 1 - i]; // pay for the dearest, take the cheapest free
}
return vector<int>{mn, mx};
}
};Python
class Solution:
def candyStore(self, candies: list[int], k: int) -> list[int]:
c = sorted(candies)
paid = (len(c) + k) // (k + 1) # each bought candy brings k free ones
return [sum(c[:paid]), sum(c[len(c) - paid:])] # cheapest paid for / dearest paid forCommon mistakes
- Paying for
n / (k + 1)rounded down. - Taking the free candies from the wrong end.