bugfree Icon
interview-course
interview-course
interview-course
interview-course
interview-course
interview-course
interview-course
interview-course

Leetcode Problem 123. Best Time to Buy and Sell Stock III

123. Best Time to Buy and Sell Stock III

Leetcode Solutions

Approach: One-pass Simulation

  1. Initialize t1_cost to infinity and t1_profit to 0.
  2. Initialize t2_cost to infinity and t2_profit to 0.
  3. Iterate through each price in the prices array. a. Update t1_cost to be the minimum of the current t1_cost and the current price. b. Update t1_profit to be the maximum of the current t1_profit and the current price minus t1_cost. c. Update t2_cost to be the minimum of the current t2_cost and the current price minus t1_profit. d. Update t2_profit to be the maximum of the current t2_profit and the current price minus t2_cost.
  4. Return t2_profit as the maximum profit that can be achieved with at most two transactions.
UML Thumbnail

Approach: Bidirectional Dynamic Programming

Ask Question

Programming Language
image/screenshot of info(optional)
Full Screen
Loading...

Suggested Answer

Answer
Full Screen
Copy Answer Code
Loading...