Given a list containing future predictions of share prices, find the maximum profit earned by buying and selling shares at most twice with a constraint that a new transaction can only start after the previous transaction complete, i.e., we can only hold at most one share at a time.

For example,

Input:  Stock prices are {2, 4, 7, 5, 4, 3, 5}
Output: The maximum profit is 7
 
Buy at a price 2 and sell at a price 7
Buy at a price 3 and sell at a price 5
 
 
Input:  Stock prices are {10, 6, 8, 4, 2}
Output: The maximum profit is 2
 
Buy at a price 6 and sell at a price 8
 
 
Input:  Stock prices are {8, 7, 6, 4}
Output: The maximum profit is 0
 
Buying and selling stock will result in loss

Practice this problem

There are several variations to the above problem:

  1. If we are allowed to stock only once, then we can find the maximum difference between two elements in the array, where the smaller element appears before the larger element.
  2. If we are allowed to stock shares at most k times, we can follow the approach discussed here.
  3. If we are allowed to stock shares any number of times, we can follow the approach discussed here.

 
Here, we are allowed to stock shares at most twice. The idea is to use extra space to solve this problem. We create an auxiliary array profit[] and fill it while performing two scans of the input array, which contains the stock price information for each day.

  1. In the first scan, update profit[i] to the maximum profit earned by a single stock transaction from the day i till day n-1. We can do this by traversing the array from right to left and keeping track of the maximum stock price seen so far.
  2. In the second scan, update profit[i] by taking a maximum of profit[i-1] (i.e., maximum profit calculated so far), and the total profit obtained by closing the first transaction on the day i and performing another transaction from the day i till day n-1. We can find the maximum profit earned on a stock transaction closing on the day i by traversing the array from left to right and keeping track of the minimum stock price seen so far.

Finally, the last element of profit[] has the result.

 
Note that we can initiate the second transaction on the same day as closing the first transaction, i.e., at the same price. This does not violate the problem constraint that a second transaction can only start once the first transaction is complete. This essentially means that we have performed only a single transaction.

 
The algorithm can be implemented as follows in C++, Java, and Python:

C++


Download  Run Code

Output:

The maximum profit is 7

Java


Download  Run Code

Output:

The maximum profit is 7

Python


Download  Run Code

Output:

The maximum profit is 7

The time complexity of the above solution is O(n) and requires O(n) extra space, where n is the total number of given days.