LeetCode 2291: Maximum Profit From Trading Stocks Solution
Master LeetCode problem 2291 (Maximum Profit From Trading Stocks), a medium 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.
2291. Maximum Profit From Trading Stocks
Problem Explanation
Explanation:
To solve this problem, we can use a dynamic programming approach. We will maintain two variables: buy and sell. We iterate over the prices array and update these variables based on the current price. At each step, we calculate the maximum profit that can be obtained by buying at the current price and selling at a future price.
- Initialize
buyto a very large negative value andsellto 0. - Iterate over the prices array.
- Update
buyto the maximum of its current value or the negative of the current price. - Update
sellto the maximum of its current value or the sum of current price andbuy.
The final answer will be stored in the sell variable.
Time Complexity:
The time complexity of this solution is O(n), where n is the number of prices in the input array.
Space Complexity:
The space complexity of this solution is O(1) as we are using constant extra space. :
Solution Code
class Solution {
public int maxProfit(int[] prices) {
int buy = Integer.MIN_VALUE;
int sell = 0;
for (int price : prices) {
buy = Math.max(buy, -price);
sell = Math.max(sell, price + buy);
}
return sell;
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 2291 (Maximum Profit From Trading Stocks)?
This page provides optimized solutions for LeetCode problem 2291 (Maximum Profit From Trading Stocks) 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 2291 (Maximum Profit From Trading Stocks)?
The time complexity for LeetCode 2291 (Maximum Profit From Trading Stocks) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 2291 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 2291 in Java, C++, or Python.