Open In App

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:



Approach 1: Naive 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.

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






function maxProfit(price, n) {
  
    // Create profit array and
    // initialize it as 0
    let profit = new Array(n);
    for (let i = 0; i < n; i++)
        profit[i] = 0;
  
    /* Get the maximum profit with
    only one transaction
    allowed. After this loop,
    profit[i] contains maximum
    profit from price[i..n-1]
    using at most one trans. */
    let max_price = price[n - 1];
    for (let i = n - 2; i >= 0; i--) {
  
        // Max_price has maximum
        // of price[i..n-1]
        if (price[i] > max_price)
            max_price = price[i];
  
        // We can get profit[i] by taking maximum of:
        // a) previous maximum, i.e., profit[i+1]
        // b) profit by buying at price[i] and selling at
        // max_price
        profit[i] = Math.max(profit[i + 1],
            max_price - price[i]);
    }
  
    // Get the maximum profit with
    // two transactions allowed
    // After this loop, profit[n-1]
    // contains the result
    let min_price = price[0];
    for (let i = 1; i < n; i++) {
  
        // min_price is minimum price
        // in price[0..i]
        if (price[i] < min_price)
            min_price = price[i];
  
        // Maximum profit is maximum of:
        // a) previous maximum, i.e., profit[i-1]
        // b) (Buy, Sell) at (min_price, price[i]) and add
        // profit of other trans. stored in profit[i]
        profit[i] = Math.max(profit[i - 1],
            profit[i] + (price[i] - min_price));
    }
    let result = profit[n - 1];
  
    return result;
}
  
// Driver code
let price = [2, 30, 15, 10, 8, 25, 80];
let n = price.length;
  
console.log("Maximum Profit = " +
    maxProfit(price, n));

Output
Maximum Profit = 100

Time complexity: O(n)

Auxiliary space: O(n)

Approach 2: 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.




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)


Article Tags :