Tech & SaaS
Senior
programming
LeetCode #123 - Best Time to Buy and Sell Stock III
You are given an array where the ith element is the price of a given stock on day i. Design an algorithm to find the best time to buy and sell stock to maximize profit. You may complete at most two transactions. Return the maximum profit you can achieve.
Input:
prices = [3,2,6,5,0,3]
Output:
Max Profit: 7
Constraints:
1 <= prices.length <= 10^5
0 <= prices[i] <= 10^5
```
## Approach
Utilize dynamic programming to calculate potential profits for two transactions. Maintain two arrays for profits: one for max profit up to a particular day and the other for profit achievable after the day.
## Complexity
**Time:** O(n)
**Space:** O(n)
## Trade-offs
- Space complexity can be optimized by reducing space usage to O(1) by maintaining only necessary variables.
```
Trusted by 100+ professionals preparing for interviews
Trusted by 100+ professionals
50+ Company Question Banks
5+ Supported Languages
Practice More Questions Like This
Generate unlimited interview questions with structured answers, code runner, and AI-powered walkthroughs.
Get Started Free
More Tech & SaaS Interview Prep
Describe a time when you had to advocate for a technical decision that differed from the consensus of your team. What was the decision, and how did you handle the pushback?
Tech & SaaS · Senior
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.