The Wayback Machine - https://web.archive.org/web/20240818163937/https://www.geeksforgeeks.org/maximum-profit-by-buying-and-selling-a-share-at-most-twice/
Open In App

Best Time to Buy and Sell Stock III (at most two transactions allowed)

Last Updated : 11 Jun, 2024
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

In daily share trading, 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.

Examples: 

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

Input:   price[] = {100, 30, 15, 10, 8, 25, 80};
Output:  72
Buy at price 8 and sell at 80.

Input:   price[] = {90, 80, 70, 60, 50}\
Output:  0
Not possible to earn.

Naive approach: A Simple Solution is to consider every index ‘i’ and do the following 

Max profit with at most two transactions = 
MAX {max profit with one transaction and subarray price[0..i] + 
max profit with one transaction and subarray price[i+1..n-1] } 
i varies from 0 to n-1.

The maximum possible using one transaction can be calculated using the following O(n) algorithm 
The maximum difference between two elements such that the larger element appears after the smaller number
Time Complexity: O(n2).

Efficient Solution. The idea is to store the maximum possible profit of every subarray and solve the problem in the following two phases.

1) Create a table profit[0..n-1] and initialize all values in it 0.
2) Traverse price[] from right to left and update profit[i] such that profit[i] stores maximum profit achievable from one transaction in subarray price[i..n-1]
3) Traverse price[] from left to right and update profit[i] such that profit[i] stores maximum profit such that profit[i] contains maximum achievable profit from two transactions in subarray price[0..i].
4) Return profit[n-1]

To do step 2, we need to keep track of the maximum price from right to left side, and to do step 3, we need to keep track of the minimum price from left to right. Why we traverse in reverse directions? The idea is to save space, in the third step, we use the same array for both purposes, maximum with 1 transaction and maximum with 2 transactions. After iteration i, the array profit[0..i] contains the maximum profit with 2 transactions, and profit[i+1..n-1] contains profit with two transactions.

Below are the implementations of the above approach.

C++
// C++ program to find maximum
// possible profit with at most
// two transactions
#include <bits/stdc++.h>
using namespace std;

// Returns maximum profit with
// two transactions on a given
// list of stock prices, price[0..n-1]
int maxProfit(int price[], int n)
{
    // Create profit array and
    // initialize it as 0
    int* profit = new int[n];
    for (int 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. */
    int max_price = price[n - 1];
    for (int 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]
            = 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 */
    int min_price = price[0];
    for (int 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] = max(profit[i - 1],
                        profit[i] + (price[i] - min_price));
    }
    int result = profit[n - 1];

    delete[] profit; // To avoid memory leak

    return result;
}

// Driver code
int main()
{
    int price[] = { 2, 30, 15, 10, 8, 25, 80 };
    int n = sizeof(price) / sizeof(price[0]);
    cout << "Maximum Profit = " << maxProfit(price, n);
    return 0;
}
Java
import java.io.*;

class Profit {
    // Returns maximum profit
    // with two transactions on a
    // given list of stock prices,
    // price[0..n-1]
    static int maxProfit(int price[], int n)
    {
        // Create profit array
        // and initialize it as 0
        int profit[] = new int[n];
        for (int 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. */
        int max_price = price[n - 1];
        for (int 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
         */
        int min_price = price[0];
        for (int 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));
        }
        int result = profit[n - 1];
        return result;
    }

    // Driver Code
    public static void main(String args[])
    {
        int price[] = { 2, 30, 15, 10, 8, 25, 80 };
        int n = price.length;
        System.out.println("Maximum Profit = "
                           + maxProfit(price, n));
    }

} /* This code is contributed by Rajat Mishra */
Python
# Returns maximum profit with
# two transactions on a given
# list of stock prices price[0..n-1]


def maxProfit(price, n):

    # Create profit array and initialize it as 0
    profit = [0]*n

    # 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.
    max_price = price[n-1]

    for i in range(n-2, 0, -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] = 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
    min_price = price[0]

    for i in range(1, n):

        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, A[i]) and add
        #  profit of other trans.
        # stored in profit[i]
        profit[i] = max(profit[i-1], profit[i]+(price[i]-min_price))

    result = profit[n-1]

    return result


# Driver function
price = [2, 30, 15, 10, 8, 25, 80]
print ("Maximum profit is", maxProfit(price, len(price)))

# This code is contributed by __Devesh Agrawal__
C#
// C# program to find maximum possible profit
// with at most two transactions
using System;

class GFG {

    // Returns maximum profit with two
    // transactions on a given list of
    // stock prices, price[0..n-1]
    static int maxProfit(int[] price, int n)
    {

        // Create profit array and initialize
        // it as 0
        int[] profit = new int[n];
        for (int 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. */
        int max_price = price[n - 1];

        for (int 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 */
        int min_price = price[0];

        for (int 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));
        }
        int result = profit[n - 1];

        return result;
    }

    // Driver code
    public static void Main()
    {
        int[] price = { 2, 30, 15, 10, 8, 25, 80 };
        int n = price.Length;

        Console.Write("Maximum Profit = "
                      + maxProfit(price, n));
    }
}

// This code is contributed by nitin mittal.
JavaScript
<script>

// JavaScript program to find maximum
// possible profit with at most
// two transactions

// Returns maximum profit with
// two transactions on a given
// list of stock prices, price[0..n-1]
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;

document.write("Maximum Profit = " + 
               maxProfit(price, n));

// This code is contributed by Surbhi Tyagi.

</script>
PHP
<?php
// PHP program to find maximum 
// possible profit with at most 
// two transactions

// Returns maximum profit with 
// two transactions on a given 
// list of stock prices, price[0..n-1] 
function maxProfit($price, $n) 
{
    // Create profit array and
    // initialize it as 0 
    $profit = array(); 
    for ($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. 
    $max_price = $price[$n - 1]; 
    for ($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 
        if($profit[$i + 1] >
           $max_price-$price[$i])
        $profit[$i] = $profit[$i + 1]; 
        else
        $profit[$i] = $max_price -
                      $price[$i];
    } 

    // Get the maximum profit with 
    // two transactions allowed. 
    // After this loop, profit[n-1] 
    // contains the result 
    $min_price = $price[0]; 
    for ($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] = max($profit[$i - 1], 
                          $profit[$i] + 
                         ($price[$i] - $min_price)); 
    } 
    $result = $profit[$n - 1]; 
    return $result; 
}

// Driver Code 
$price = array(2, 30, 15, 10,
               8, 25, 80); 
$n = sizeof($price); 
echo "Maximum Profit = ". 
      maxProfit($price, $n); 
    
// This code is contributed
// by Arnab Kundu
?>

Output
Maximum Profit = 100

Time complexity: O(n)
Auxiliary space: O(n) 

Algorithmic Paradigm: Dynamic Programming 

Another approach:

Initialize four variables for taking care of the first buy, first sell, second buy, second sell. Set first buy and second buy as INT_MIN and first and second sell as 0. This is to ensure to get profit from transactions. Iterate through the array and return the second sell as it will store maximum profit.

C++
#include <iostream>
#include<climits>
using namespace std;

int maxtwobuysell(int arr[],int size) {
    int first_buy = INT_MIN;
      int first_sell = 0;
      int second_buy = INT_MIN;
      int second_sell = 0;
      
      for(int i=0;i<size;i++) {
        
          first_buy = max(first_buy,-arr[i]);//we set prices to negative, so the calculation of profit will be convenient
          first_sell = max(first_sell,first_buy+arr[i]); 
          second_buy = max(second_buy,first_sell-arr[i]);//we can buy the second only after first is sold
          second_sell = max(second_sell,second_buy+arr[i]);
      
    }
     return second_sell;
}

int main() {

    int arr[] = {2, 30, 15, 10, 8, 25, 80};
      int size = sizeof(arr)/sizeof(arr[0]);
      cout<<maxtwobuysell(arr,size);
    return 0;
}
Java
import java.util.*;
class GFG{

static int maxtwobuysell(int arr[],int size) {
    int first_buy = Integer.MIN_VALUE;
      int first_sell = 0;
      int second_buy = Integer.MIN_VALUE;
      int second_sell = 0;
      
      for(int i = 0; i < size; i++) {
        
          first_buy = Math.max(first_buy,-arr[i]); 
          first_sell = Math.max(first_sell,first_buy+arr[i]); 
          second_buy = Math.max(second_buy,first_sell-arr[i]);
          second_sell = Math.max(second_sell,second_buy+arr[i]);
      
    }
     return second_sell;
}

public static void main(String[] args)
{
    int arr[] = {2, 30, 15, 10, 8, 25, 80};
      int size = arr.length;
      System.out.print(maxtwobuysell(arr,size));
}
}

// This code is contributed by gauravrajput1 
Python
import sys

def maxtwobuysell(arr, size):
    first_buy = -sys.maxsize; 
    first_sell = 0;
    second_buy = -sys.maxsize; 
    second_sell = 0;

    for i in range(size):

        first_buy = max(first_buy, -arr[i]);
        first_sell = max(first_sell, first_buy + arr[i]);
        second_buy = max(second_buy, first_sell - arr[i]);
        second_sell = max(second_sell, second_buy + arr[i]);

    
    return second_sell;

if __name__ == '__main__':
    arr = [ 2, 30, 15, 10, 8, 25, 80 ];
    size = len(arr);
    print(maxtwobuysell(arr, size));

# This code is contributed by gauravrajput1 
C#
using System;

public class GFG{

static int maxtwobuysell(int []arr,int size) {
    int first_buy = int.MinValue;
      int first_sell = 0;
      int second_buy = int.MinValue;
      int second_sell = 0;
      
      for(int i = 0; i < size; i++) {
        
          first_buy = Math.Max(first_buy,-arr[i]); 
          first_sell = Math.Max(first_sell,first_buy+arr[i]); 
          second_buy = Math.Max(second_buy,first_sell-arr[i]);
          second_sell = Math.Max(second_sell,second_buy+arr[i]);
      
    }
     return second_sell;
}

public static void Main(String[] args)
{
    int []arr = {2, 30, 15, 10, 8, 25, 80};
      int size = arr.Length;
      Console.Write(maxtwobuysell(arr,size));
}
}

// This code is contributed by gauravrajput1 
JavaScript
<script>
    function maxtwobuysell(arr , size) {
        var first_buy = -1000;
        var first_sell = 0;
        var second_buy = -1000;
        var second_sell = 0;

        for (var i = 0; i < size; i++) {

            first_buy = Math.max(first_buy, -arr[i]);
            first_sell = Math.max(first_sell, first_buy + arr[i]);
            second_buy = Math.max(second_buy, first_sell - arr[i]);
            second_sell = Math.max(second_sell, second_buy + arr[i]);

        }
        return second_sell;
    }

    
        var arr = [ 2, 30, 15, 10, 8, 25, 80 ];
        var size = arr.length;
        document.write(maxtwobuysell(arr, size));

// This code is contributed by gauravrajput1
</script>

Output
100

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

Recursive Approach :

Every day, 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.

C++
#include <bits/stdc++.h>

using namespace std;

int f(int idx, int buy, int prices[],
       int cap, int n)
{
    if (cap == 0) {
        return 0;
    }

    if (idx == n) {
        return 0;
    }



    int profit = 0;
    // you can either buy or not buy
    if (buy == 0) {
      profit
            = 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 = max(
            prices[idx]
                + f(idx + 1, 0, prices, cap - 1, n),
            f(idx + 1, 1, prices,  cap, n));
    }

    return profit;
}

int maxtwobuysell(int prices[], int n)
{
    return f(0, 0, prices, 2, n);
}

int main()
{

    int arr[] = { 2, 30, 15, 10, 8, 25, 80 };
    int size = sizeof(arr) / sizeof(arr[0]);
    cout << maxtwobuysell(arr, size);
    return 0;
}
Java
import java.util.*;

public class Main {

  static int f(int idx, int buy, int prices[],
               int cap, int n)
  {
      if (cap == 0) {
          return 0;
      }

      if (idx == n) {
          return 0;
      }

      int 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;
  }

  static int maxtwobuysell(int prices[], int n)
  {
      return f(0, 0, prices, 2, n);
  }

  public static void main(String[] args)
  {

      int arr[] = { 2, 30, 15, 10, 8, 25, 80 };
      int size = arr.length;
      System.out.println(maxtwobuysell(arr, size));
  }
}

// This code is contributed by prajwalkandekar123.
Python
def f(idx, buy, prices, cap, n):
    if cap == 0:
        return 0

    if idx == n:
        return 0

    profit = 0
    # you can either buy or not buy
    if buy == 0:
        profit = 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 = max(prices[idx] + f(idx + 1, 0, prices, cap - 1, n),
                     f(idx + 1, 1, prices, cap, n))

    return profit

def maxtwobuysell(prices, n):
    return f(0, 0, prices, 2, n)


if __name__ == "__main__":
    arr = [2, 30, 15, 10, 8, 25, 80]
    size = len(arr)
    print(maxtwobuysell(arr, size))

    # This code is contributed by prajwalkandekar123.
C#
using System;

class MainClass {
    public static int f(int idx, int buy, int[] prices,
                        int cap, int n)
    {
        if (cap == 0) {
            return 0;
        }

        if (idx == n) {
            return 0;
        }

        int 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;
    }

    public static int maxtwobuysell(int[] prices, int n)
    {
        return f(0, 0, prices, 2, n);
    }

    public static void Main()
    {
        int[] arr = new int[] { 2, 30, 15, 10, 8, 25, 80 };
        int size = arr.Length;
        Console.WriteLine(maxtwobuysell(arr, size));
    }
}
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)

Memoization Approach: 

Exact same code as above just store the answer of all states to avoid solving subproblems that have already been solved
 

C++
#include <bits/stdc++.h>

using namespace std;

int f(int idx, int buy, int prices[],
      vector<vector<vector<int> > >& dp, int cap, int n)
{
    if (cap == 0) {
        return 0;
    }

    if (idx == n) {
        return 0;
    }

    if (dp[idx][buy][cap] != -1) {
        return dp[idx][buy][cap];
    }

    int profit = 0;
    // you can either buy or not buy
    if (buy == 0) {
        dp[idx][buy][cap] = profit
            = max(-prices[idx]
                      + f(idx + 1, 1, prices, dp, cap, n),
                  f(idx + 1, 0, prices, dp, cap, n));
    }
    // you can either sell or not sell
    else {
        dp[idx][buy][cap] = profit = max(
            prices[idx]
                + f(idx + 1, 0, prices, dp, cap - 1, n),
            f(idx + 1, 1, prices, dp, cap, n));
    }

    return profit;
}

int maxtwobuysell(int prices[], int n)
{

    vector<vector<vector<int> > > dp(
        n, vector<vector<int> >(2, vector<int>(3, -1)));
    return f(0, 0, prices, dp, 2, n);
}

int main()
{

    int arr[] = { 2, 30, 15, 10, 8, 25, 80 };
    int size = sizeof(arr) / sizeof(arr[0]);
    cout << maxtwobuysell(arr, size);
    return 0;
}
Java
import java.util.*;

public class Main {

    public static int
    f(int idx, int buy, int[] prices,
      ArrayList<ArrayList<ArrayList<Integer> > > dp,
      int cap, int n)
    {

        if (cap == 0) {
            return 0;
        }

        if (idx == n) {
            return 0;
        }

        if (dp.get(idx).get(buy).get(cap) != -1) {
            return dp.get(idx).get(buy).get(cap);
        }

        int profit = 0;

        // you can either buy or not buy
        if (buy == 0) {
            dp.get(idx).get(buy).set(
                cap,
                profit = Math.max(
                    -prices[idx]
                        + f(idx + 1, 1, prices, dp, cap, n),
                    f(idx + 1, 0, prices, dp, cap, n)));
        }
        // you can either sell or not sell
        else {
            dp.get(idx).get(buy).set(
                cap,
                profit = Math.max(
                    prices[idx]
                        + f(idx + 1, 0, prices, dp, cap - 1,
                            n),
                    f(idx + 1, 1, prices, dp, cap, n)));
        }

        return profit;
    }

    public static int maxtwobuysell(int[] prices, int n)
    {
        ArrayList<ArrayList<ArrayList<Integer> > > dp
            = new ArrayList<>(n);
        for (int i = 0; i < n; i++) {
            dp.add(new ArrayList<>(2));
            for (int j = 0; j < 2; j++) {
                dp.get(i).add(new ArrayList<>(3));
                for (int k = 0; k < 3; k++) {
                    dp.get(i).get(j).add(-1);
                }
            }
        }
        return f(0, 0, prices, dp, 2, n);
    }

    public static void main(String[] args)
    {

        int[] arr = { 2, 30, 15, 10, 8, 25, 80 };
        int size = arr.length;
        System.out.println(maxtwobuysell(arr, size));
    }
}
Python
# Python program for the above approach
import sys

def f(idx, buy, prices, dp, cap, n):
    if cap == 0:
        return 0
    if idx == n:
        return 0
    if dp[idx][buy][cap] != -1:
        return dp[idx][buy][cap]

    profit = 0
    
    # you can either buy or not buy
    if buy == 0:
        dp[idx][buy][cap] = profit = max(-prices[idx] + 
                                         f(idx + 1, 1, prices, dp, cap, n), 
                                         f(idx + 1, 0, prices, dp, cap, n))
    
    # you can either sell or not sell
    else:
        dp[idx][buy][cap] = profit = max(prices[idx] + 
                                         f(idx + 1, 0, prices, dp, cap - 1, n),
                                         f(idx + 1, 1, prices, dp, cap, n))

    return profit

def maxtwobuysell(prices, n):
    dp = [[[-1 for _ in range(3)] for _ in range(2)] for _ in range(n)]
    return f(0, 0, prices, dp, 2, n)

if __name__ == "__main__":
    arr = [2, 30, 15, 10, 8, 25, 80]
    size = len(arr)
    print(maxtwobuysell(arr, size))


# This code is contributed by rishabmalhdjio
C#
using System;

class MainClass {
  static int f(int idx, int buy, int[] prices,
               int[][][] dp, int cap, int n) {
    if (cap == 0) {
      return 0;
    }

    if (idx == n) {
      return 0;
    }

    if (dp[idx][buy][cap] != -1) {
      return dp[idx][buy][cap];
    }

    int profit = 0;
    // you can either buy or not buy
    if (buy == 0) {
      dp[idx][buy][cap] = profit =
        Math.Max(-prices[idx]
                 + f(idx + 1, 1, prices, dp, cap, n),
                 f(idx + 1, 0, prices, dp, cap, n));
    }
    // you can either sell or not sell
    else {
      dp[idx][buy][cap] = profit = Math.Max(
        prices[idx]
        + f(idx + 1, 0, prices, dp, cap - 1, n),
        f(idx + 1, 1, prices, dp, cap, n));
    }

    return profit;
  }

  static int maxtwobuysell(int[] prices, int n) {
    int[][][] dp = new int[n][][];
    for (int i = 0; i < n; i++) {
      dp[i] = new int[2][];
      for (int j = 0; j < 2; j++) {
        dp[i][j] = new int[3];
        for (int k = 0; k < 3; k++) {
          dp[i][j][k] = -1;
        }
      }
    }
    return f(0, 0, prices, dp, 2, n);
  }

  public static void Main() {
    int[] arr = { 2, 30, 15, 10, 8, 25, 80 };
    int size = arr.Length;
    Console.WriteLine(maxtwobuysell(arr, size));
  }
}
// This code is contributed by divyansh2212
JavaScript
// JavaScript implementation
function f(idx, buy, prices, dp, cap, n) {
    if (cap == 0) {
        return 0;
    }
    if (idx == n) {
        return 0;
    }
    if (dp[idx][buy][cap] != -1) {
        return dp[idx][buy][cap];
    }
    
    let profit = 0;
    
    // you can either buy or not buy
    if (buy == 0) {
        dp[idx][buy][cap] = profit = Math.max(-prices[idx] + 
                                             f(idx + 1, 1, prices, dp, cap, n),
                                             f(idx + 1, 0, prices, dp, cap, n));
    } else {
        // you can either sell or not sell
        dp[idx][buy][cap] = profit = Math.max(prices[idx] + 
                                             f(idx + 1, 0, prices, dp, cap - 1, n),
                                             f(idx + 1, 1, prices, dp, cap, n));
    }
    
    return profit;
}

function maxtwobuysell(prices, n) {
    const dp = Array.from(Array(n), () => Array.from(Array(2), () => Array(3).fill(-1)));
    return f(0, 0, prices, dp, 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(N)
Auxiliary Space : O(N)



Previous Article
Next Article

Similar Reads

Best Time to Buy and Sell Stock IV (at most k transactions allowed)
In share trading, a buyer buys shares and sells on a future date. Given the stock price of n days, the trader is allowed to make at most k transactions, where a new transaction can only start after the previous transaction is complete, find out the maximum profit that a share trader could have made. Examples: Input: Price = [10, 22, 5, 75, 65, 80],
15+ min read
Best Time to Buy and Sell Stock II (infinite transactions allowed)
Given an array prices[] of size N denoting the cost of stock on each day, the task is to find the maximum total profit if we can buy and sell the stocks any number of times. Note: We can only sell a stock which we have bought earlier and we cannot hold multiple stocks on any day. Examples: Input: prices[] = {100, 180, 260, 310, 40, 535, 695}Output:
15 min read
Best Time to Buy and Sell Stock (at most one transaction allowed)
Given an array prices[] of length N, representing the prices of the stocks on different days, the task is to find the maximum profit possible by buying and selling the stocks on different days when at most one transaction is allowed. Note: Stock must be bought before being sold. Examples: Input: prices[] = {7, 1, 5, 3, 6, 4}Output: 5Explanation:The
14 min read
Best Time to Buy and Sell Stock VI (with transaction fee)
Given an array of positive integers containing the price of stocks and transaction fee, the task is to find the maximum profit and the difference of days on which you are getting the maximum profit.  Examples:  Input: arr[] = {6, 1, 7, 2, 8, 4}, transactionFee = 2Output: 8 1Explanation: Buy on day 2 at 1 and sell at day 3 at 7. Again, buy on day 4
14 min read
Best Time to Buy and Sell Stock V (with cooldown)
Given the prices of stock for n number of days. Every ith day tell the price of the stock on that day. Find the maximum profit that you can make by buying and selling stock with the restriction of after you sell your stock, you cannot buy stock on the next day (i.e., cooldown one day). Examples: Input: arr[] = {1, 2, 3, 0, 2}Output : 3Explanation:
6 min read
Stock Buy and Sell Problems with Variations
You might have encountered a lot of problems where the user can buy and sell stocks with certain restrictions. In this article, we are going to list all such variations of Stock Problems. Best Time to Buy and Sell Stock (at most one transaction allowed):In this problem, we are given an array prices[], where prices[i] denotes the price of stock on i
5 min read
Javascript Program For Stock Buy Sell To Maximize Profit
The cost of a stock on each day is given in an array, find the max profit that you can make by buying and selling in those days. For example, if the given array is {100, 180, 260, 310, 40, 535, 695}, the maximum profit can earned by buying on day 0, selling on day 3. Again buy on day 4 and sell on day 6. If the given array of prices is sorted in de
4 min read
Job Scheduling with two jobs allowed at a time
We are given N jobs, and their starting and ending times. We can do two jobs simultaneously at a particular moment. If one job ends at the same moment some other show starts then we can't do them. We need to check if it is possible to complete all the jobs or not.Examples: Input : Start and End times of Jobs 1 2 2 3 4 5 Output : Yes By the time thi
7 min read
Maximum profit by buying and selling a stock at most twice | Set 2
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 y
10 min read
Queries to replace subarrays by equal length arrays with at most P replacements allowed for any array element
Given an array, arr[] of size N, an integer P and a 2D array Q[][] consisting of queries of the following type: 1 L R B[R - L + 1]: The task for this query is to replace the subarray {arr[L], ... arr[R] with the array B[] b given that any array element can be replaced at most P times.2 X: The task for this query is to print arr[X]. Examples: Input:
15+ min read
Minimum swaps to reach permuted array with at most 2 positions left swaps allowed
Given a permuted array of length N of first N natural numbers, we need to tell the minimum number of swaps required in the sorted array of first N natural number to reach given permuted array where a number can be swapped with at most 2 positions left to it. If it is not possible to reach permuted array by above swap condition then print not possib
14 min read
Longest Common Subsequence with at most k changes allowed
Given two sequence P and Q of numbers. The task is to find Longest Common Subsequence of two sequences if we are allowed to change at most k element in first sequence to any value. Examples: Input : P = { 8, 3 } Q = { 1, 3 } K = 1 Output : 2 If we change first element of first sequence from 8 to 1, both sequences become same. Input : P = { 1, 2, 3,
8 min read
Minimum time required to complete all tasks with alteration of their order allowed
Given a string S consisting of N characters (representing the tasks to perform) and a positive integer K, the task is to find the minimum time required to complete all the given tasks in any order, given that each task takes one unit of time and each task of the same type must be performed at an interval of K units. Examples: Input: S = "AAABBB", K
8 min read
Minimum time to reach from Node 1 to N if travel is allowed only when node is Green
Given an undirected connected graph of N nodes and M edges. Each node has a light but at a time it can be either green or red. Initially, all the node is of green color. After every T seconds, the color of light changes from green to red and vice-versa. It is possible to travel from node U to node V only if the color of node U is green. The time ta
10 min read
Maximize count of distinct profits possible by N transactions
Given three integers N, X, and Y, representing the total number of transactions, minimum and maximum profit respectively, the task is to find the count of distinct total profits that can be earned in N ( N &gt; 1) transactions using X and Y at least once. Examples: Input: N = 3, X = 13, Y = 15Output: 3Explanation: The different possible transaction
4 min read
Merge transactions in bank sheets in the order of their occurrence such that their sum remains positive
Given an array arr[][] consisting of N lists representing N transactions, the task is to merge the given lists of transactions in the order of their occurrences, such that at any point of time, the sum of already performed transactions is non-negative. If found to negative, then print "-1". Otherwise, print the merged list of transactions. Examples
7 min read
Buy minimum items without change and given coins
You have an unlimited number of 10-rupee coins and exactly one coin of r rupee and you need to buy minimum items each of cost k such that you do not ask for change.Examples: Input: k = 15, r = 2 Output: 2 You should buy two cables and pay 2*15=30 rupees. It is obvious that you can pay this sum without any change.Input: k = 237, r = 7 Output:1 It is
4 min read
Find the minimum and maximum amount to buy all N candies
In a candy store, there are N different types of candies available and the prices of all the N different types of candies are provided. There is also an attractive offer by the candy store. We can buy a single candy from the store and get at most K other candies (all are different types) for free. Find the minimum amount of money we have to spend t
11 min read
Time difference between expected time and given time
Given the initial clock time h1:m1 and the present clock time h2:m2, denoting hour and minutes in 24-hours clock format. The present clock time h2:m2 may or may not be correct. Also given a variable K which denotes the number of hours passed. The task is to calculate the delay in seconds i.e. time difference between expected time and given time. Ex
5 min read
Minimize cost to buy N elements using given cost Array
Given 2 arrays num[] and cost[] containing the number of elements and the cost to buy that many elements respectively. {i.e. cost[i] is the cost to buy num[i] elements}. The task is to minimize the cost to buy exactly N elements. Examples: Input: num[] = [1, 2, 10, 50], cost[] = [400, 750, 3250, 15000], N = 7Output: 2650Explanation: The minimum amo
15+ min read
Minimum money required to buy items with given cashbacks
Given an array arr[] of length N, denoting the cost of N items and the cashback upon buying that item, the task is to find the minimum amount of money required to buy all the items irrespective of the order in which they are bought. Examples: Input: arr[] = [ [ 7, 2 ], [ 10, 5 ], [ 2, 1] ] Output: 16Explanation: The geek can buy the goodies in the
6 min read
Minimum cost to buy N kilograms of sweet for M persons
Given an array of n sizes, it includes the cost of sweets in such a way that sweet[i] is the cost of i sweets. The task is to find the minimum cost to spend to buy exactly 'n' kilograms of sweets for the 'm' people. Since sweets are available in packets, you have to buy at most a 'm' packet of sweets for your 'm' relatives. You cannot buy more than
15+ min read
Find minimum cost to buy all books
Given an array of ratings for n books. Find the minimum cost to buy all books with below conditions : Cost of every book would be at-least 1 dollar.A book has higher cost than an adjacent (left or right) if rating is more than the adjacent. Examples : Input : Ratings[] = {1, 3, 4, 3, 7, 1} Output : 10 Exp :- 1 + 2 + 3 + 1 + 2 + 1 = 10 Input : ratin
6 min read
Buy Maximum Stocks if i stocks can be bought on i-th day
In a stock market, there is a product with its infinite stocks. The stock prices are given for N days, where arr[i] denotes the price of the stock on the ith day. There is a rule that a customer can buy at most i stock on the ith day. If the customer has k amount of money initially, find out the maximum number of stocks a customer can buy. For exam
6 min read
Minimum cost to buy all items at least once
Given an array A[] of length N. Consider that purchasing ith item will cost Ai and then next i number of item(s) will be free to collect. Then your task is to output the minimum cost to collect all items at least once. Examples: Input: A[] = {3 ,1, 2} Output: 4 Explanation: Consider an imaginary array Collected[] to track collected items, collected
7 min read
Minimum cost to reach a point N from 0 with two different operations allowed
Given integers N, P and Q where N denotes the destination position. The task is to move from position 0 to position N with minimum cost possible and print the calculated cost. All valid movements are: From position X you can go to position X + 1 with a cost of POr, you can go to the position 2 * X with a cost of Q Examples: Input: N = 1, P = 3, Q =
6 min read
Find maximum path sum in a 2D matrix when exactly two left moves are allowed
Given a 2D matrix arr[][] of dimensions N * M where N is number of rows and M is number of columns.The task is to find maximum path sum in this matrix satisfying some condition which are as follows : We can only start with arr[i][M] where 0 &lt;= i &lt;= N.We end the path on the same side, such that we can take exactly 2 left turns.First we calcula
2 min read
Check if a destination is reachable from source with two movements allowed | Set 2
Given a pair of coordinates (X1, Y1)(source) and (X2, Y2)(destination), the task is to check if it is possible to reach the destination form the source by the following movements from any cell (X, Y): (X + Y, Y)(X, Y + X) Note: All coordinates are positive and can be as large as 1018. Examples: Input: X1 = 2, Y1 = 10, X2 = 26, Y2 = 12 Output: Yes E
7 min read
Maximum points collected by two persons allowed to meet once
Given a 2-D matrix A[N][M] where A[i][j] denotes the points available on this cell. Two persons, P1 and P2, start from two corners of this matrix. P1 starts from top left and needs to reach bottom right. On the other hand, P2 starts bottom left and needs to reach top right. P1 can move right and down. P2 can right and up. As they visit a cell, poin
13 min read
Check if a destination is reachable from source with two movements allowed
Given coordinates of a source point (x1, y1) determine if it is possible to reach the destination point (x2, y2). From any point (x, y) there only two types of valid movements: (x, x + y) and (x + y, y). Return a boolean true if it is possible else return false. Note: All coordinates are positive. Asked in: Expedia, TelstraExamples: Input : (x1, y1
5 min read
three90RightbarBannerImg