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)

๐Ÿ› ๏ธ 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

๐Ÿ“š Reference Solution

โ–ผ
โŒ˜K Search โŒ˜โ†ฉ Run โŒ˜S Submit