
Problem
Solution
Submissions
Best Time to Buy and Sell Stock III
Certification: Advanced Level
Accuracy: 100%
Submissions: 1
Points: 15
Write a Java program to find the maximum profit that can be achieved by performing at most two transactions (buying and selling a stock). You are given an array prices where prices[i] is the price of a given stock on the ith day. You may complete at most two transactions, i.e., you may buy and sell the stock twice. You cannot engage in multiple transactions simultaneously (you must sell the stock before you buy again). Return the maximum profit.
Example 1
- Input: prices = [3,3,5,0,0,3,1,4]
- Output: 6
- Explanation: Buy on day 3 (price = 0) and sell on day 5 (price = 3), profit = 3 Buy on day 6 (price = 1) and sell on day 7 (price = 4), profit = 3 Total profit = 3 + 3 = 6
Example 2
- Input: prices = [1,2,3,4,5]
- Output: 4
- Explanation: Buy on day 0 (price = 1) and sell on day 4 (price = 5), profit = 4 No second transaction is performed. Total profit = 4
Constraints
- 1 <= prices.length <= 10^5
- 0 <= prices[i] <= 10^5
- You can make at most two transactions
- Time Complexity: O(n)
- Space Complexity: O(1)
Editorial
My Submissions
All Solutions
| Lang | Status | Date | Code |
|---|---|---|---|
| You do not have any submissions for this problem. | |||
| User | Lang | Status | Date | Code |
|---|---|---|---|---|
| No submissions found. | ||||
Solution Hints
- Use a dynamic programming approach to track the maximum profit after different buy/sell operations
- Track four variables representing different states: first buy, first sell, second buy, second sell
- Update each state based on the previous state and the current price
- Initialize first buy and second buy as -∞ (or a very negative number) as we start with no stock
- The maximum profit will be the value of the second sell state at the end