LeetCode 123: Best Time to Buy and Sell Stock III Solution
Master LeetCode problem 123 (Best Time to Buy and Sell Stock III), a hard challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
123. Best Time to Buy and Sell Stock III
Problem Explanation
Explanation
To solve this problem, we can use dynamic programming. We will maintain four variables to keep track of the maximum profit we can achieve after each transaction. At each day, we update these variables based on the prices.
buy1: The maximum profit after the first buy.sell1: The maximum profit after the first sell.buy2: The maximum profit after the second buy.sell2: The maximum profit after the second sell.
We iterate through the prices array and update these variables accordingly. At the end, sell2 will hold the maximum profit we can achieve after two transactions.
Time Complexity: O(n), where n is the number of elements in the prices array.
Space Complexity: O(1)
Solution Code
class Solution {
public int maxProfit(int[] prices) {
int buy1 = Integer.MIN_VALUE, sell1 = 0;
int buy2 = Integer.MIN_VALUE, sell2 = 0;
for (int price : prices) {
buy1 = Math.max(buy1, -price);
sell1 = Math.max(sell1, buy1 + price);
buy2 = Math.max(buy2, sell1 - price);
sell2 = Math.max(sell2, buy2 + price);
}
return sell2;
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 123 (Best Time to Buy and Sell Stock III)?
This page provides optimized solutions for LeetCode problem 123 (Best Time to Buy and Sell Stock III) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 123 (Best Time to Buy and Sell Stock III)?
The time complexity for LeetCode 123 (Best Time to Buy and Sell Stock III) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 123 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 123 in Java, C++, or Python.