gfg_potd

GFG Problem Of The Day

Date - 24 December, 2023

Ques - Buy Maximum Stocks if i stocks can be bought on i-th day

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.

Approach Used :

- 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.

Example : N = 3, k = 45, arr = [10, 7, 19]

Output : 4

Explanation:

Time and Auxiliary Space Complexity

Code (C++)

class 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;
    }
};

Contribution and Support

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.

Total number of repository visitors

Total number of repository stars