AlgoMaster Logo

Best Time to Buy and Sell Stock III

Ashish

Ashish Pratap Singh

hard

Problem Description

Solve it on LeetCode

Approaches

1. Brute Force

The brute force approach would involve checking every possible combination of two transactions (buy-sell pairs) to find the maximum profit. However, this approach is highly inefficient since it would require iterating over all possible pairs of transactions.

Complexity Analysis:

  • Time Complexity: O(N^4), where N is the number of days. This is because the approach involves checking each pair of days for both transactions, resulting in a nested iteration.
  • Space Complexity: O(1), no extra space is used aside from a few variables.

2. Dynamic Programming with State Machine

Intuition:

  • We need an optimal way to calculate profits with at most two transactions.
  • We define states based on whether we have completed transactions or holding stocks.

State Definitions:

  • 0: before any transaction,
  • 1: holding stock after the first buy,
  • 2: completed the first sell,
  • 3: holding stock after the second buy,
  • 4: completed the second sell.

Each day, we determine the best action based on states defined above.

Code:

3. Optimized Dynamic Programming

Intuition:

  • We can reduce the space complexity by using only two variables for each state since each state depends only on the previous day.

Code: