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

27 Aug, 2021
In a stock market, there is a product with its infinite stocks. The stock prices are given for N days, where arr[i] denotes the price of the stock on the ith day. There is a rule that a customer can buy at most i stock on the ith day. If the customer has an amount of k amount of money initially, find out the maximum number of stocks a customer can buy. 
For example, for 3 days the price of a stock is given as 7, 10, 4. You can buy 1 stock worth 7 rs on day 1, 2 stocks worth 10 rs each on day 2 and 3 stock worth 4 rs each on day 3.
Examples: 
Input : price[] = { 10, 7, 19 }, 
              k = 45.
Output : 4
A customer purchases 1 stock on day 1, 
2 stocks on day 2 and 1 stock on day 3 for 
10, 7 * 2 = 14 and 19 respectively. Hence, 
total amount is 10 + 14 + 19 = 43 and number 
of stocks purchased is 4.

Input  : price[] = { 7, 10, 4 }, 
               k = 100.
Output : 6
The idea is to use greedy approach, where we should start buying product from the day when the stock price is least and so on. So, we will sort the pair of two values i.e { stock price, day } according to the stock price, and if stock prices are same, then we sort according to the day. Now, we will traverse along the sorted list of pairs, and start buying as follows: Let say, we have R rs remaining till now, and the cost of product on this day be C, and we can buy atmost L products on this day then, total purchase on this day (P) = min(L, R/C) Now, add this value to the answer. total purchase on this day (P) = min(L, R/C) Now, add this value to the answer total_purchase = total_purchase + P, where P =min(L, R/C) Now, subtract the cost of buying P items from remaining money, R = R – P*C. Total number of products that we can buy is equal to total_purchase.
Below is the implementation of this approach:  
C++
Java
Python3
// C++ program to find maximum number of stocks that// can be bought with given constraints.#include <bits/stdc++.h>using namespace std; // Return the maximum stocksint buyMaximumProducts(int n, int k, int price[]){    vector<pair<int, int> > v;     // Making pair of product cost and number    // of day..    for (int i = 0; i < n; ++i)        v.push_back(make_pair(price[i], i + 1));        // Sorting the vector pair.    sort(v.begin(), v.end());        // Calculating the maximum number of stock    // count.    int ans = 0;    for (int i = 0; i < n; ++i) {        ans += min(v[i].second, k / v[i].first);        k -= v[i].first * min(v[i].second,                               (k / v[i].first));    }     return ans;} // Driven Programint main(){    int price[] = { 10, 7, 19 };    int n = sizeof(price)/sizeof(price[0]);    int k = 45;     cout << buyMaximumProducts(n, k, price) << endl;     return 0;}
// Java program to find maximum number of stocks that// can be bought with given constraints.import java.util.*; // Helper classclass Pair {    int first, second;    Pair(int first, int second)    {        this.first = first;        this.second = second;    }} // For Sorting using Pair.first valueclass SortPair implements Comparator<Pair> {    public int compare(Pair a, Pair b)    {        return a.first - b.first;    }} public class GFG {     // Return the maximum stocks    static int buyMaximumProducts(int[] price, int K, int n)    {        Pair[] arr = new Pair[n];         // Making pair of product cost and number of day..        for (int i = 0; i < n; i++)            arr[i] = new Pair(price[i], i + 1);         // Sorting the pair array.        Arrays.sort(arr, new SortPair());        // Calculating the maximum number of stock        // count.        int ans = 0;        for (int i = 0; i < n; i++) {            ans += Math.min(arr[i].second,                            K / arr[i].first);            K -= arr[i].first                 * Math.min(arr[i].second,                            K / arr[i].first);        }        return ans;    }   // Driver code    public static void main(String[] args)    {        int[] price = { 10, 7, 19 };        int K = 45;               // int []price = { 7, 10, 4 };        // int K = 100;        System.out.println(            buyMaximumProducts(price, K, price.length));    }} // This code is contributed by Aakash Choudhary
# Python3 program to find maximum number of stocks# that can be bought with given constraints. # Returns the maximum stocksdef buyMaximumProducts(n, k, price):     # Making pair of stock cost and day number    arr = []         for i in range(n):        arr.append([i + 1, price[i]])     # Sort based on the price of stock    arr.sort(key = lambda x: x[1])         # Calculating the max stocks purchased    total_purchase = 0    for i in range(n):        P = min(arr[i][0], k//arr[i][1])        total_purchase += P        k -= (P * arr[i][1])     return total_purchase # Driver codeprice = [ 10, 7, 19 ]n = len(price)k = 45   print(buyMaximumProducts(n, k, price)) # This code is contributed by Tharun Reddy
Output: 
4
Time Complexity :O(nlogn).
This article is contributed by Anuj Chauhan. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. 
Akanksha_Rai
tharun07
molterous
Greedy
Greedy
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Huffman Coding | Greedy Algo-3
Activity Selection Problem | Greedy Algo-1
Fractional Knapsack Problem
Program for Shortest Job First (or SJF) CPU Scheduling | Set 1 (Non- preemptive)
Job Sequencing Problem
Dijkstra’s Algorithm for Adjacency List Representation | Greedy Algo-8
Difference between Prim's and Kruskal's algorithm for MST
Program for Least Recently Used (LRU) Page Replacement algorithm
Shortest Remaining Time First (Preemptive SJF) Scheduling Algorithm
Minimum Number of Platforms Required for a Railway/Bus Station