702074. Stock Buy and Sell – Multiple Transaction Allowed

Medium

Stock Buy and Sell – Multiple Transaction Allowed

Summary

The problem is to find the maximum possible profit that can be achieved from a given stock price array, allowing for multiple transactions (buy and sell) at any time. The key concepts involved are arrays and dynamic programming.

Detailed Explanation

The approach to this problem involves using dynamic programming to keep track of the maximum possible profit after each transaction. Let's break it down step by step:

  1. Initialize two arrays, max_ending_here and max_so_far, both initialized with 0.
  2. Iterate through the stock price array. For each day:
    • Calculate the maximum possible profit if we sell on this day (max_ending_here[i] = max(max_ending_here[i-1] + (price[i] - price[i-1]), 0)) and update max_ending_here accordingly.
    • Update max_so_far to be the maximum of its current value and max_ending_here.
  3. Return the maximum possible profit, which is stored in max_so_far.

Here's an ASCII art diagram illustrating this approach:

  +---------------+
  |  Day i-1    |
  +---------------+
           |
           |  max_ending_here[i-1]
           v
  +---------------+
  |  Day i      |
  +---------------+
           |
           |  (price[i] - price[i-1])
           v
  +---------------+
  |  max_ending_here[i]  |
  +---------------+
           |
           |  max_so_far = max(max_ending_here[i], max_so_far)
           v
  +---------------+
  |  ...      |
  +---------------+

Time complexity: O(n), where n is the number of days in the stock price array. Space complexity: O(1), since we only use a constant amount of space to store the arrays.

Optimized Solutions

Here are optimized solutions for this problem in various languages:

Java

View on GeeksforGeeks
public int maxProfit(int[] prices) {
    if (prices.length < 2) return 0;
    int maxSoFar = 0, maxEndingHere = 0;
    for (int i = 1; i < prices.length; i++) {
        maxEndingHere = Math.max(maxEndingHere + prices[i] - prices[i-1], 0);
        maxSoFar = Math.max(maxSoFar, maxEndingHere);
    }
    return maxSoFar;
}

DevExCode

Master coding interviews with Leetcode, system design, TechBit, QuickLearn, DevTips, Tech Battles, and career services.

© 2026 DevExCode. All rights reserved.