HARD 1-D Dynamic Programming
123. Best Time to Buy and Sell Stock III
๐ Problem
You are given an array prices where prices[i] is the price of a given stock on the ith day. Find the maximum profit you can achieve. You may complete at most two transactions. Note: You may not engage in multiple transactions at the same time (i.e., you must sell the stock before you buy again).
๐ง Visual Learning Aid
1 Model the input into the right structure
2 Choose the core technique and invariant
3 Execute step-by-step with a sample
4 Validate complexity and edge cases
JS/TS Refreshers
- โขArray methods (`push`, `pop`, `shift`, `slice`)
- โขObject/Map/Set usage patterns
- โขFunction parameter and return typing
- โขArray DP table updates
- โขState transition thinking
- โขBase case initialization
Logical Thinking Concepts
- โขDefine invariants before coding
- โขCheck edge cases first (`[]`, single element, duplicates)
- โขEstimate time/space before implementation
- โขApply Dynamic Programming reasoning pattern
๐ก Approach
- โ Track 4 states: first buy, first sell, second buy, second sell
- โ buy1 = max profit after first buy (negative)
- โ sell1 = max profit after first sell
- โ buy2 = max profit after second buy
- โ sell2 = max profit after second sell (final answer)
- โ Time: O(n), Space: O(1)
๐งญ Prerequisites
๐ ๏ธ Hints & Pitfalls
Hints
- โขTrack 4 states: first buy, first sell, second buy, second sell
- โขbuy1 = max profit after first buy (negative)
- โขsell1 = max profit after first sell
Common Pitfalls
- โขbuy2 = max profit after second buy
- โขsell2 = max profit after second sell (final answer)
- โขTime: O(n), Space: O(1)
๐งช Test Cases
Hidden tests on submit: 1
Test Case 1
Not run Input:
maxProfit([3,3,5,0,0,3,1,4]); Expected:
6 Test Case 2
Not run Input:
maxProfit([1,2,3,4,5]); Expected:
4 Test Case 3
Not run Input:
maxProfit([7,6,4,3,1]); Expected:
0 ๐ Code Editor
๐ค Output