In a stock market, there is a product with its infinite stocks. The stock prices are given for N days, where price[i] denotes the price of the stock on the ith day.
- Goal is to buy maximum number of stocks, so we buy stocks from the cheapest to more expensive, hence sorting is required but we have to keep the index in mind.
- First form a list stock with (price, index). For this question, the index is also the maximum number of this stock we can buy at this price.
- Sort the list by price.
- We keep buying stock from the beginning of the list until we run out of money.
O(NLogN)
, because of sorting the vector arrayO(N)
, vector array sizeclass Solution {
public:
int buyMaximumProducts(int n, int k, int price[]) {
vector<pair<int, int>> v;
for (int i = 0; i < n; ++i)
v.push_back({price[i], i + 1});
sort(v.begin(), v.end());
int count = 0;
for (auto i : v) {
int maxBuy = min(k / i.first, i.second);
count += maxBuy;
k -= i.first * maxBuy;
}
return count;
}
};
If you have a better solution or any queries / discussions , please visit our discussion section.
If you find this solution helpful, consider supporting us by giving a ⭐ star
to the SHRbharat/gfg_potd repository.