Open In App

Stock Buy and Sell - Multiple Transaction Allowed

Last Updated : 03 Oct, 2025
Comments
Improve
Suggest changes
249 Likes
Like
Report

Given an array prices[] representing stock prices, find the maximum total profit that can be earned by buying and selling the stock 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: 865
Explanation: Buy the stock on day 0 and sell it on day 3 = 310 - 100 = 210 and Buy the stock on day 4 and sell it on day 6 = 695 - 40 = 655 so the Maximum Profit is = 210 + 655 = 865.

total_profit

Input: prices[] = [4, 2]
Output: 0
Explanation: Stock prices keep decreasing, there is no chance to sell at a higher price after buying, so no profit can be made.

[Naive Approach] By Trying All Possibility - O(2n) Time and O(n) Space

The idea is to use recursion to simulate all choices of buying and selling. For each day, you can either skip it or buy on that day. If you buy at day i, then you try all possible selling days j > i where price[j] > price[i].

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

// Recursive function to find max profit
int maxProfitRec(vector<int> &price, int start, int end) {
    int res = 0;

    // Try every possible pair of buy (i) and sell (j)
    for (int i = start; i < end; i++) {
        for (int j = i + 1; j <= end; j++) {
            
            // Valid transaction if selling price > buying price
            if (price[j] > price[i]) {
               
                // Current profit + profit from left and right parts
                int curr = (price[j] - price[i]) +
                           maxProfitRec(price, start, i - 1) +
                           maxProfitRec(price, j + 1, end);
                res = max(res, curr);
            }
        }
    }
    return res;
}

int maxProfit(vector<int> &prices) {
    return maxProfitRec(prices, 0, prices.size() - 1);
}

int main() {
    vector<int> prices = {100, 180, 260, 310, 40, 535, 695};
    cout << maxProfit(prices);
    return 0;
}
Java
public class GFG {

    // Recursive function to find max profit
    static int maxProfitRec(int[] price, int start, int end) {
        int res = 0;

        // Try every possible pair of buy (i) and sell (j)
        for (int i = start; i < end; i++) {
            for (int j = i + 1; j <= end; j++) {
               
                // Valid transaction if selling price > buying price
                if (price[j] > price[i]) {
               
                    // Current profit + profit from left and right parts
                    int curr = (price[j] - price[i]) +
                               maxProfitRec(price, start, i - 1) +
                               maxProfitRec(price, j + 1, end);
                    res = Math.max(res, curr);
                }
            }
        }
        return res;
    }

    static int maxProfit(int[] prices) {
        return maxProfitRec(prices, 0, prices.length - 1);
    }

    public static void main(String[] args) {
        int[] prices = {100, 180, 260, 310, 40, 535, 695};
        System.out.println(maxProfit(prices));
    }
}
Python
def maxProfitRec(price, start, end):
    res = 0

    # Try every possible pair of buy (i) and sell (j)
    for i in range(start, end):
        for j in range(i + 1, end + 1):
         
            # Valid transaction if selling price > buying price
            if price[j] > price[i]:
                curr = (price[j] - price[i]) + \
                       maxProfitRec(price, start, i - 1) + \
                       maxProfitRec(price, j + 1, end)
                res = max(res, curr)
    return res

def maxProfit(prices):
    return maxProfitRec(prices, 0, len(prices) - 1)

if __name__ == "__main__":
    prices = [100, 180, 260, 310, 40, 535, 695]
    print(maxProfit(prices))
C#
using System;

class GFG {
    
    // Recursive function to find max profit
    static int maxProfitRec(int[] price, int start, int end) {
        int res = 0;

        // Try every possible pair of buy (i) and sell (j)
        for (int i = start; i < end; i++)
        {
            for (int j = i + 1; j <= end; j++)
            {
                // Valid transaction if selling price > buying price
                if (price[j] > price[i])
                {
                    int curr = (price[j] - price[i]) +
                               maxProfitRec(price, start, i - 1) +
                               maxProfitRec(price, j + 1, end);
                    res = Math.Max(res, curr);
                }
            }
        }
        return res;
    }

    static int maxProfit(int[] prices) {
        return maxProfitRec(prices, 0, prices.Length - 1);
    }

    static void Main()
    {
        int[] prices = { 100, 180, 260, 310, 40, 535, 695 };
        Console.WriteLine(maxProfit(prices));
    }
}
JavaScript
function maxProfitRec(price, start, end) {
    let res = 0;

    // Try every possible pair of buy (i) and sell (j)
    for (let i = start; i < end; i++) {
        for (let j = i + 1; j <= end; j++) {
            // Valid transaction if selling price > buying price
            if (price[j] > price[i]) {
                let curr = (price[j] - price[i]) +
                           maxProfitRec(price, start, i - 1) +
                           maxProfitRec(price, j + 1, end);
                res = Math.max(res, curr);
            }
        }
    }
    return res;
}

function maxProfit(prices) {
    return maxProfitRec(prices, 0, prices.length - 1);
}
// Driver Code
let prices = [100, 180, 260, 310, 40, 535, 695];
console.log(maxProfit(prices));

Output
865

[Better Approach] Using Local Minima and Maxima - O(n) Time and O(1) Space

The idea is to traverse the array from left to right and Find local minima (where price starts rising) and then a local maxima (where price stops rising). Compute the difference between two and add to the result.

Below is the implementation of the algorithm

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

int maxProfit(vector<int>& prices) {
    int n = prices.size();
    
     // Local Minima
    int lMin = prices[0]; 
    
    // Local Maxima
    int lMax = prices[0];  
    int res = 0;
  
    int i = 0;
    while (i < n - 1) {
      
        // Find local minima 
        while (i < n - 1 && prices[i] >= prices[i + 1]) { i++; }
        lMin = prices[i];
       
        // Local Maxima
        while (i < n - 1 && prices[i] <= prices[i + 1]) { i++; }
        lMax = prices[i];
      
        // Add current profit 
        res = res + (lMax - lMin);
    }
  
    return res;
}

int main() {
    vector<int> prices = {100, 180, 260, 310, 40, 535, 695};
    cout << maxProfit(prices);
    return 0;
}
C
#include <stdio.h>

int maxProfit(int prices[], int n) {
    int lMin = prices[0];  
    int lMax = prices[0]; 
    int res = 0;
  
    int i = 0;
    while (i < n - 1) {
      
        // Find local minima
        while (i < n - 1 && prices[i] >= prices[i + 1]) { i++; }
        lMin = prices[i];
       
        // Local Maxima
        while (i < n - 1 && prices[i] <= prices[i + 1]) { i++; }
        lMax = prices[i];
      
        // Add current profit
        res += (lMax - lMin);
    }
  
    return res;
}

// Driver Code
int main() {
    int prices[] = {100, 180, 260, 310, 40, 535, 695};
    int n = sizeof(prices) / sizeof(prices[0]);
    printf("%d\n", maxProfit(prices, n));
    return 0;
}
Java
class GfG {
  
    static int maxProfit(int[] prices) {
        int n = prices.length;
        int lMin = prices[0];  
        int lMax = prices[0];  
        int res = 0;

        int i = 0;
        while (i < n - 1) {
          
            // Find local minima
            while (i < n - 1 && prices[i] >= prices[i + 1]) { i++; }
            lMin = prices[i];
           
            // Local Maxima
            while (i < n - 1 && prices[i] <= prices[i + 1]) { i++; }
            lMax = prices[i];
          
            // Add current profit
            res += (lMax - lMin);
        }
      
        return res;
    }

    public static void main(String[] args) {
        int[] prices = {100, 180, 260, 310, 40, 535, 695};
        System.out.println(maxProfit(prices));
    }
}
Python
def maxProfit(prices):
    n = len(prices)
    lMin = prices[0]  
    lMax = prices[0]  
    res = 0
  
    i = 0
    while i < n - 1:
      
        # Find local minima
        while i < n - 1 and prices[i] >= prices[i + 1]:
            i += 1
        lMin = prices[i]
        
        # Local Maxima
        while i < n - 1 and prices[i] <= prices[i + 1]:
            i += 1
        lMax = prices[i]
      
        # Add current profit
        res += (lMax - lMin)
  
    return res

if __name__ == "__main__":
    prices = [100, 180, 260, 310, 40, 535, 695]
    print(maxProfit(prices))
C#
using System;

class GfG {

    static int maxProfit(int[] prices) {
        int n = prices.Length;
        int lMin = prices[0]; 
        int lMax = prices[0];  
        int res = 0;

        int i = 0;
        while (i < n - 1) {
          
            // Find local minima
            while (i < n - 1 && prices[i] >= prices[i + 1]) { i++; }
            lMin = prices[i];
           
            // Local Maxima
            while (i < n - 1 && prices[i] <= prices[i + 1]) { i++; }
            lMax = prices[i];
          
            // Add current profit
            res += (lMax - lMin);
        }
      
        return res;
    }

    static void Main() {
        int[] prices = {100, 180, 260, 310, 40, 535, 695};
        Console.WriteLine(maxProfit(prices));
    }
}
JavaScript
function maxProfit(prices) {
    let n = prices.length;
    let lMin = prices[0];  
    let lMax = prices[0];  
    let res = 0;
  
    let i = 0;
    while (i < n - 1) {
      
        // Find local minima
        while (i < n - 1 && prices[i] >= prices[i + 1]) { i++; }
        lMin = prices[i];
       
        // Local Maxima
        while (i < n - 1 && prices[i] <= prices[i + 1]) { i++; }
        lMax = prices[i];
      
        // Add current profit
        res += (lMax - lMin);
    }
  
    return res;
}

// Driver Code 
const prices = [100, 180, 260, 310, 40, 535, 695];
console.log(maxProfit(prices));

Output
865

[Expected Approach] By Accumulating Profit - O(n) Time and O(1) Space

The idea is that profit only comes when prices rise. If the price goes up from one day to the next, we can think of it as buying yesterday and selling today. Instead of waiting for the exact bottom and top, we simply grab every small upward move. Adding these small gains together is the same as if we had bought at each valley and sold at each peak because every rise between them gets counted.


Below is the implementation of the algorithm:

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

int maxProfit(const vector<int>& prices) {
    int res = 0;
  
    // Keep on adding the difference between
    // adjacent when the prices a
    for (int i = 1; i < prices.size(); i++) {
        if (prices[i] > prices[i - 1]) 
            res += prices[i] - prices[i - 1];
    }
    
    return res;
}

int main() {
    vector<int> prices = { 100, 180, 260, 310, 40, 535, 695 };
    cout << maxProfit(prices) << endl;
    return 0;
}
C
#include <stdio.h>

int maxProfit(const int* prices, int n) {
    int res = 0;

    // Keep on adding the difference between
    // adjacent when the prices a
    for (int i = 1; i < n; i++) {
        if (prices[i] > prices[i - 1]) 
            res += prices[i] - prices[i - 1];
    }
    
    return res;
}

int main() {
    int prices[] = { 100, 180, 260, 310, 40, 535, 695 };
    int size = sizeof(prices) / sizeof(prices[0]);
    printf("%d\n", maxProfit(prices, size));
    return 0;
}
Java
import java.util.Arrays;

class GfG {
    
    static int maxProfit(int[] prices) {
        int res = 0;

        // Keep on adding the difference between
        // adjacent when the prices a
        for (int i = 1; i < prices.length; i++) {
            if (prices[i] > prices[i - 1]) 
                res += prices[i] - prices[i - 1];
        }
        
        return res;
    }

    public static void main(String[] args) {
        int[] prices = { 100, 180, 260, 310, 40, 535, 695 };
        System.out.println(maxProfit(prices));
    }
}
Python
def maxProfit(prices):
    res = 0

    # Keep on adding the difference between
    # adjacent when the prices a
    for i in range(1, len(prices)):
        if prices[i] > prices[i - 1]:
            res += prices[i] - prices[i - 1]

    return res

if __name__ == "__main__":
    prices = [100, 180, 260, 310, 40, 535, 695]
    print(maxProfit(prices))
C#
using System;
using System.Collections.Generic;

class GfG {
    static int maxProfit(List<int> prices) {
        int res = 0;

        // Keep on adding the difference between
        // adjacent when the prices a
        for (int i = 1; i < prices.Count; i++) {
            if (prices[i] > prices[i - 1]) 
                res += prices[i] - prices[i - 1];
        }

        return res;
    }

    static void Main(string[] args) {
        List<int> prices = 
             new List<int> { 100, 180, 260, 310, 40, 535, 695 };
        Console.WriteLine(maxProfit(prices));
    }
}
JavaScript
function maxProfit(prices) {
    let res = 0;

    // Keep on adding the difference between
    // adjacent when the prices a
    for (let i = 1; i < prices.length; i++) {
        if (prices[i] > prices[i - 1]) 
            res += prices[i] - prices[i - 1];
    }

    return res;
}

// Driver Code 
const prices = [100, 180, 260, 310, 40, 535, 695];
console.log(maxProfit(prices));

Output
865

Stock Buy and Sell (With No Limit)
Visit Course explore course icon

Explore