LeetCode 122: Best Time to Buy and Sell Stock II Solution
Master LeetCode problem 122 (Best Time to Buy and Sell Stock II), 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.
122. Best Time to Buy and Sell Stock II
Problem Explanation
Explanation
To find the maximum profit that can be achieved by buying and selling stocks, we can iterate through the prices array and whenever there is a price increase from the previous day, we can add that increase to the total profit. This is because we are allowed to buy and sell multiple times.
Algorithm:
- Initialize
totalProfitto 0. - Iterate through the prices array starting from index 1:
- If the price on the current day is higher than the price on the previous day, add the difference to
totalProfit.
- If the price on the current day is higher than the price on the previous day, add the difference to
- Return
totalProfit.
Time Complexity: The time complexity of this solution is O(n), where n is the number of elements in the prices array.
Space Complexity: The space complexity is O(1) as we are using only a constant amount of extra space.
Solution Code
class Solution {
public int maxProfit(int[] prices) {
int totalProfit = 0;
for (int i = 1; i < prices.length; i++) {
if (prices[i] > prices[i - 1]) {
totalProfit += prices[i] - prices[i - 1];
}
}
return totalProfit;
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 122 (Best Time to Buy and Sell Stock II)?
This page provides optimized solutions for LeetCode problem 122 (Best Time to Buy and Sell Stock II) 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 122 (Best Time to Buy and Sell Stock II)?
The time complexity for LeetCode 122 (Best Time to Buy and Sell Stock II) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 122 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 122 in Java, C++, or Python.