LeetCode 121: Best Time to Buy and Sell Stock Solution

Master LeetCode problem 121 (Best Time to Buy and Sell Stock), a easy 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.

121. Best Time to Buy and Sell Stock

Problem Explanation

Explanation

To solve this problem, we can use a simple approach of iterating through the array and keeping track of the minimum price seen so far and the maximum profit that can be achieved by selling at the current price. We update the maximum profit whenever we find a new peak price that gives a better profit.

  • Start with the first element of the array as the minimum price and the maximum profit as 0.
  • Iterate through the array starting from the second element:
    • Update the minimum price seen so far.
    • Calculate the profit that can be achieved by selling at the current price.
    • Update the maximum profit if the current profit is greater.
  • Return the maximum profit as the result.

Time Complexity: O(n), where n is the number of elements in the array.

Space Complexity: O(1)

Solution Code

class Solution {
    public int maxProfit(int[] prices) {
        int minPrice = Integer.MAX_VALUE;
        int maxProfit = 0;
        
        for (int price : prices) {
            minPrice = Math.min(minPrice, price);
            maxProfit = Math.max(maxProfit, price - minPrice);
        }
        
        return maxProfit;
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 121 (Best Time to Buy and Sell Stock)?

This page provides optimized solutions for LeetCode problem 121 (Best Time to Buy and Sell Stock) 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 121 (Best Time to Buy and Sell Stock)?

The time complexity for LeetCode 121 (Best Time to Buy and Sell Stock) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 121 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 121 in Java, C++, or Python.

Back to LeetCode Solutions