5.Best Time to Buy and Sell Stock

Problem 1: (SingleTransactions)

Say you have an array for which the ith element is the price of a given stock on day i.

If you were only permitted to complete at most one transaction (i.e., buy one and sell one share of the stock), design an algorithm to find the maximum profit. i.e Maximum difference between two elements such that larger element appears after the smaller number.

Example 1:
Input: [7,1,5,3,6,4]
Output: 5
Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5.
             Not 7-1 = 6, as selling price needs to be larger than buying price.


Example 2:
Input: [7,6,4,3,1]
Output: 0
Explanation: In this case, no transaction is done, i.e. max profit = 0.

Solution I

class Solution
{
public:
    int maxProfit(vector<int> &arr)
    {

        int maxDiff = INT_MIN;
        for (int i = 0; i < arr.size(); i++)
        {
            for (int j = i + 1; j < arr.size(); j++)
            {

                if (arr[j] - arr[i] > maxDiff)
                {
                    maxDiff = arr[j] - arr[i];
                }
            }
        }
        
        if(maxDiff<=0){
            return 0;
        }
        
        return maxDiff;
    }
};

Time Complexity: O(n^2)

Solution II

Algo: Keep track of 2 things: 1) Maximum difference found so far (max_diff). 2) Minimum number visited so far (min_element).

class Solution
{
public:
    int maxProfit(vector<int> &arr)
    {
        
        if(arr.size()==0){return 0;}

        int maxDiff = 0;
        int minEle = arr[0];

        for (int i = 1; i < arr.size(); i++)
        {
            if (arr[i] - minEle > maxDiff)
            {
                maxDiff = arr[i] - minEle;
            }

            if (arr[i] < minEle)
            {
                minEle = arr[i];
            }
        }

        return maxDiff;
    }
};

Time Complexity: O(n)

Problem 2: (Multiple Transactions)

Design an algorithm to find the maximum profit. You may complete as many transactions as you like (i.e., buy one and sell one share of the stock multiple times).

Example 1:
Input: [7,1,5,3,6,4]
Output: 7
Explanation: Buy on day 2 (price = 1) and sell on day 3 (price = 5), profit = 5-1 = 4.
             Then buy on day 4 (price = 3) and sell on day 5 (price = 6), profit = 6-3 = 3.

Example 2:
Input: [1,2,3,4,5]
Output: 4
Explanation: Buy on day 1 (price = 1) and sell on day 5 (price = 5), profit = 5-1 = 4.
             Note that you cannot buy on day 1, buy on day 2 and sell them later, as you are
             engaging multiple transactions at the same time. You must sell before buying again.
             
Example 3:
Input: [7,6,4,3,1]
Output: 0
Explanation: In this case, no transaction is done, i.e. max profit = 0.

Solution :

Algo:

  1. Find the local minima and store it as starting index. If not exists, return.

  2. Find the local maxima. and store it as ending index. If we reach the end, set the end as ending index.

  3. Update the solution (Increment count of buy sell pairs)

  4. Repeat the above steps if end is not reached.

class Solution
{
public:
    int maxProfit(vector<int> &arr)
    {

        int n = arr.size();

        vector<pair<int, int>> v;

        int i = 0;
        while (i < n)
        {
            //fidning local minimum
            while (i < n - 1 && arr[i] >= arr[i+1])
            {
                i++;
            }

            int buy = i;
            if (i == n - 1)
            {
                break;
            }

            i++;
            
            //fidning local maximum
            while (i < n-1 && arr[i] <= arr[i + 1])
            {
                i++;
            }
            
            int sell = i;
            v.push_back(make_pair(arr[buy], arr[sell]));
        }

        int res = 0;
        for (int j = 0; j < v.size(); j++)
        {
            int b = v[j].first;
            int s = v[j].second;
            res = res + s - b;
        }
        return res;
    }
};

Time Complexity: O(n)

Last updated