# Maximum profit by buying and selling a stock at most twice | Set 2

• Difficulty Level : Medium
• Last Updated : 06 May, 2021

Given an array prices[] which denotes the prices of the stocks on different days, the task is to find the maximum profit possible after buying and selling the stocks on different days using transaction where at most two transactions are allowed.
Note: You cannot engage in multiple transactions at the same time (i.e., you must sell the stock before you buy again).

Examples:

Input: prices[] = {3, 3, 5, 0, 0, 3, 1, 4}
Output:
Explanation:
Buy on Day 4 and Sell at Day 6 => Profit = 3 – 0 = 3
Buy on Day 7 and Sell at Day 8 => Profit = 4 -1 = 3
Therefore, Total Profit = 3 + 3 = 6

Input: prices[] = {1, 2, 3, 4, 5}
Output:
Explanation:
Buy on Day 1 and sell at Day 6 => Profit = 5 -1 = 4
Therefore, Total Profit = 4

Efficient Approach: The idea used here is to keep track of the two transactions at the same time. The two stocks profit is computed as follows

• Maximum Profit for the First Transaction
• Find the minimum price we have to pay from our pocket (buy1) to get 1st stock which is the price of the stock on that day or on any previous day.
• Find the maximum profit by selling the 1st stock which on the current day.
• Maximum profit for the second Transaction
• The minimum price we have to pay from our pocket to buy second stocks will be
// Profit 1 is the profit from
// selling the first stock
• Find the maximum profit (profit2) by selling the 2nd stock.

Explanation with Example:

Let us take price[] = { 3, 5, 4, 5}
We buy 1st stock on day 1
We sell 1st stock on day 2.
profit1 = 5 – 3 = 2.
We will make a profit of 2 after buying the stock on 1st day and selling on 2nd day.
So, profit1 = 2
Now we will buy the 2nd stock on 3rd day
Stock price on 3rd day is 4
Since we already made a profit of 2, We will spend only 2 extra from our packet to buy the stock
i.e., (4 – profit1) = 2
Now, we will sell second stock on day 4.
Stock price on 4th day is 5.
profit2 = 5 – buy2 = 5 – 2 = 3.
Now, we can see that the final profit includes the profit of buying and selling two stocks

Below is the implementation of the above approach:

## Javascript



Output:

Maximum Profit = 100

Time complexity: O(N)
Auxiliary Space: O(1)

My Personal Notes arrow_drop_up