DevHireLab
TutorialsBootcamp
Problems
Code SimulatorAI InterviewSoonContact
DevHireLab
TutorialsBootcamp
Problems
Code SimulatorAI InterviewSoonContact
Back to Arena
hard
DP

Best Time to Buy/Sell Stock III (2 Transactions)

**Problem Statement:** Given the required input arguments, write an efficient algorithm to solve the **Best Time to Buy/Sell Stock III (2 Transactions)** problem. Implement the required logic as specified by standard definitions for this classic algorithmic challenge. **Hint / Expected Approach:** State machine: 4 states (buy1/sell1/buy2/sell2) **Edge Cases to Consider:** - (1) Prices strictly decreasing (no profit) - (2) One profitable transaction - (3) All same prices

Examples

Example 1
Input: [3,3,5,0,0,3,1,4]
Output: 6
Explanation: Buy at 0, sell at 3; buy at 1, sell at 4
Example 2
Input: [1,2,3,4,5]
Output: 4
Explanation: One transaction: buy 1, sell 5
Example 3
Input: [7,6,4,3,1]
Output: 0
Explanation: No profit possible

Constraints

  • ▪Input arguments are within valid ranges
  • ▪Optimize for execution speed
  • ▪Handle null/empty inputs gracefully

Watch Out For Edge Cases

  • ▪Prices strictly decreasing (no profit)
  • ▪One profitable transaction
  • ▪All same prices
Frequently Asked At
AmazonGoogleMicrosoftMeta