Member-only story
Best Time To Buy And Sell Stock 📈 3— Two Stocks Allowed | Coding Interview | Brute Force
Previously, we discussed the buying and selling a stock problem when we were allowed to perform only one transaction. Then, we saw the problem where we were allowed as many transactions as we want. Now let’s discuss the next version, which is a bit tricky. I will try to explain this in a very simple and detailed manner. So this article will be lengthy; bear it with me :).
Description
We are given a list of prices where prices[i] is the price of a stock on the ith day. We can make at most two transactions with one transaction at a time. Meaning we cannot hold two stocks, we have to sell the stock before buying it again.
Our goal is to find the maximum profit we can make when we are given prices of a particular stock for n consecutive days.
Let’s look at some examples to make the problem clear.
- Example 1:Input: prices = [ 2, 3, 5, 0, 0, 3, 1, 5]
Output: 8Explanation: We buy for the first transaction on day 1 at a price of 2 and sell on day 3 at a price of 5 to get a profit of 3. We again buy on day 4 at a price of 0 and sell at the cost…