Recursive Approach

In this approach, we have two choices: Buy/Sell this stock OR ignore it and move to the next one. Along with day, we also need to maintain a capacity variable which will tell us how many transactions are remaining and it will be of which type (Buy or Sell). According to that we will make recursive calls and calculate the answer. We can do at most 4 transactions (Buy, Sell, Buy, Sell) in this order.

Example: This example shows the use of the above-explained approach.

Javascript




function f(idx, buy, prices, cap, n) {
  
    if (cap == 0) {
        return 0;
    }
  
    if (idx == n) {
        return 0;
    }
  
    let profit = 0;
  
    // You can either buy or not buy
    if (buy == 0) {
        profit = Math.max(
            -prices[idx] + f(idx + 1, 1, prices, cap, n),
            f(idx + 1, 0, prices, cap, n)
        );
    }
    // You can either sell or not sell
    else {
        profit = Math.max(
            prices[idx] + f(idx + 1, 0, prices, cap - 1, n),
            f(idx + 1, 1, prices, cap, n)
        );
    }
  
    return profit;
}
  
function maxtwobuysell(prices, n) {
    return f(0, 0, prices, 2, n);
}
  
const arr = [2, 30, 15, 10, 8, 25, 80];
const size = arr.length;
console.log(maxtwobuysell(arr, size));


Output

100

Time Complexity : O(2^N)

Auxiliary Space : O(N)



JavaScript Program to Find Maximum Profit by Buying and Selling a Share at Most Twice using Array

A buyer buys shares in the morning and sells them on the same day. If the trader is allowed to make at most 2 transactions in a day, the second transaction can only start after the first one is complete (Buy->sell->Buy->sell). Given stock prices throughout the day, find out the maximum profit that a share trader could have made.

Input:   price[] = {10, 22, 5, 75, 65, 80}
Output:  87
Trader earns 87 as sum of 12, 75 
Buy at 10, sell at 22, 
Buy at 5 and sell at 80
Input:   price[] = {2, 30, 15, 10, 8, 25, 80}
Output:  100
Trader earns 100 as sum of 28 and 72
Buy at price 2, sell at 30, buy at 8 and sell at 80

There are different approaches to finding maximum profit by buying and selling a share at most twice:

Table of Content

  • Naive approach:
  • Recursive Approach:

Similar Reads

Approach 1: Naive approach

...

Approach 2: Recursive Approach

In this approach, we are going to store the maximum possible profit of every subarray and solve the problem in the following two phases....

Contact Us