C++ Program For Stock Buy Sell To Maximize Profit - GeeksforGeeks

22 Dec, 2021
The cost of a stock on each day is given in an array, find the max profit that you can make by buying and selling in those days. For example, if the given array is {100, 180, 260, 310, 40, 535, 695}, the maximum profit can earned by buying on day 0, selling on day 3. Again buy on day 4 and sell on day 6. If the given array of prices is sorted in decreasing order, then profit cannot be earned at all.
Naive approach: A simple approach is to try buying the stocks and selling them on every single day when profitable and keep updating the maximum profit so far.
Below is the implementation of the above approach:
C++
// C++ implementation of the approach#include <bits/stdc++.h>using namespace std;  // Function to return the maximum profit// that can be made after buying and// selling the given stocksint maxProfit(int price[],               int start, int end){    // If the stocks can't be bought    if (end <= start)        return 0;      // Initialise the profit    int profit = 0;      // The day at which the stock    // must be bought    for (int i = start; i < end; i++)     {        // The day at which the        // stock must be sold        for (int j = i + 1; j <= end; j++)         {            // If buying the stock at ith day and            // selling it at jth day is profitable            if (price[j] > price[i])             {                // Update the current profit                int curr_profit = price[j] - price[i] +                                   maxProfit(price,                                             start, i - 1) +                                   maxProfit(price,                                             j + 1, end);                  // Update the maximum profit so far                profit = max(profit, curr_profit);            }        }    }    return profit;}  // Driver codeint main(){    int price[] = {100, 180, 260, 310,                    40, 535, 695};    int n = sizeof(price) / sizeof(price[0]);    cout << maxProfit(price, 0, n - 1);    return 0;}
Output:
865
Efficient approach: If we are allowed to buy and sell only once, then we can use following algorithm. Maximum difference between two elements. Here we are allowed to buy and sell multiple times. Following is the algorithm for this problem.  
Find the local minima and store it as starting index. If not exists, return.Find the local maxima. and store it as an ending index. If we reach the end, set the end as the ending index.Update the solution (Increment count of buy-sell pairs)Repeat the above steps if the end is not reached.
Find the local minima and store it as starting index. If not exists, return.
Find the local maxima. and store it as an ending index. If we reach the end, set the end as the ending index.
Update the solution (Increment count of buy-sell pairs)
Repeat the above steps if the end is not reached.
C++
// C++ Program to find best buying // and selling days#include <bits/stdc++.h>using namespace std;  // This function finds the buy sell// schedule for maximum profitvoid stockBuySell(int price[], int n){    // Prices must be given for at     // least two days    if (n == 1)        return;      // Traverse through given price array    int i = 0;    while (i < n - 1)     {        // Find Local Minima        // Note that the limit is (n-2) as we are        // comparing present element to the next element        while ((i < n - 1) &&                (price[i + 1] <= price[i]))            i++;          // If we reached the end, break        // as no further solution possible        if (i == n - 1)            break;          // Store the index of minima        int buy = i++;          // Find Local Maxima        // Note that the limit is (n-1) as we are        // comparing to previous element        while ((i < n) &&                (price[i] >= price[i - 1]))            i++;          // Store the index of maxima        int sell = i - 1;          cout << "Buy on day: " << buy             << "     Sell on day: " <<                 sell << endl;    }}  // Driver codeint main(){    // Stock prices on consecutive days    int price[] = {100, 180, 260,                    310, 40, 535, 695};    int n = sizeof(price) / sizeof(price[0]);      // Function call    stockBuySell(price, n);      return 0;}  // This is code is contributed by rathbhupendra
Output:
Buy on day: 0     Sell on day: 3
Buy on day: 4     Sell on day: 6
Time Complexity: The outer loop runs till I become n-1. The inner two loops increment value of I in every iteration. So overall time complexity is O(n)
Valley Peak Approach:
In this approach, we just need to find the next greater element and subtract it from the current element so that the difference keeps increasing until we reach a minimum. If the sequence is a decreasing sequence so the maximum profit possible is 0.
C++
// C++ program to implement// the above approach#include <iostream>using namespace std;  // Preprocessing helps the code // run faster#define fl(i, a, b) for (int i = a; i < b; i++)  // Function that returnint maxProfit(int* prices, int size){    // maxProfit adds up the difference     // between adjacent elements if they     // are in increasing order    int maxProfit = 0;      // The loop starts from 1 as its     // comparing with the previous    fl(i, 1, size) if (prices[i] > prices[i - 1]) maxProfit        += prices[i] - prices[i - 1];    return maxProfit;}  // Driver codeint main(){    int prices[] = {100, 180, 260,                     310, 40, 535, 695};    int N = sizeof(prices) / sizeof(prices[0]);    cout << maxProfit(prices, N) << endl;    return 0;}// This code is contributed by Kingshuk Deb
Output:
865
Time Complexity: O(n)Auxiliary Space: O(1)
Please refer complete article on Stock Buy Sell to Maximize Profit for more details!
Accolite
Amazon
Directi
Flipkart
Goldman Sachs
Hike
MakeMyTrip
Microsoft
Morgan Stanley
Ola Cabs
Oracle
Paytm
Pubmatic
Quikr
Samsung
SAP Labs
Sapient
Swiggy
Walmart
Arrays
C++ Programs
Paytm
Flipkart
Morgan Stanley
Accolite
Amazon
Microsoft
Samsung
Hike
MakeMyTrip
Ola Cabs
Oracle
Walmart
Goldman Sachs
Directi
SAP Labs
Quikr
Pubmatic
Sapient
Swiggy
Arrays
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Trapping Rain Water
Program to find sum of elements in a given array
Reversal algorithm for array rotation
Find duplicates in O(n) time and O(1) extra space | Set 1
Window Sliding Technique
Header files in C/C++ and its uses
C++ Program for QuickSort
Program to print ASCII Value of a character
How to return multiple values from a function in C or C++?
CSV file management using C++