Buy Maximum Stocks if i stocks can be bought on i-th day
Pattern: Fractional knapsack
On day i you may buy at most i stocks at that day's price, and every stock counts the same. So buy from the cheapest day first, as many as its limit and your money allow, then the next cheapest, and so on.
The problem
price[i] is the stock price on day i + 1, and on that day you may buy at most i + 1 stocks. With k money, return
the most stocks you can buy. price = [10, 7, 19], k = 45 gives 4.
Think first
- Does it matter which stocks you buy?
- Which day stretches the money furthest?
- What stops you buying more on that day?
Hints
Brute force, and why it fails
Try every number to buy on every day: exponential.
The key insight
Since all stocks are equal, spending on a cheaper one is never worse, so cheapest-first with limits is optimal.
Dry run
| money | 45 |
|---|
price [10, 7, 19], k = 45. Days by price: day 2 (7, limit 2), day 1 (10, limit 1), day 3 (19, limit 3).
Step 1 of 4
The plan
for (p, limit) sorted by p:
can = min(limit, money / p); bought += can; money -= can * p
Complexity
- Time
O(n log n)- Space
O(n)
Sorting the days dominates.
Edge cases
- Not enough money for anything: 0.
- Equal prices.
- Plenty of money: the sum of all limits.
I've built my logic, show the code
Java
import java.util.*;
class Solution {
public int buyMaximumProducts(int[] price, int k) {
int n = price.length;
Integer[] days = new Integer[n];
for (int i = 0; i < n; i++) days[i] = i;
Arrays.sort(days, (a, b) -> Integer.compare(price[a], price[b])); // cheapest day first
int bought = 0;
long money = k;
for (int d : days) {
long can = Math.min(d + 1, money / price[d]); // at most d + 1 on day d + 1, and what we can afford
bought += can;
money -= can * price[d];
}
return bought;
}
}C++
class Solution {
public:
int buyMaximumProducts(vector<int>& price, int k) {
int n = static_cast<int>(price.size());
vector<int> days(n);
for (int i = 0; i < n; i++) days[i] = i;
sort(days.begin(), days.end(), [&](int a, int b) { return price[a] < price[b]; }); // cheapest day first
int bought = 0;
long long money = k;
for (int d : days) {
long long can = min(static_cast<long long>(d + 1), money / price[d]); // the day limit, and what we can afford
bought += static_cast<int>(can);
money -= can * price[d];
}
return bought;
}
};Python
class Solution:
def buyMaximumProducts(self, price: list[int], k: int) -> int:
bought, money = 0, k
for p, limit in sorted((p, i + 1) for i, p in enumerate(price)): # cheapest day first
can = min(limit, money // p) # at most i + 1 on day i + 1, and what we can afford
bought += can
money -= can * p
return boughtCommon mistakes
- Buying day by day in order.
- Forgetting the per-day limit.