โ† Back to Index

๐Ÿ“š Best Time to Buy and Sell Stock โ€“ Java Cheat Sheet

๐Ÿ“Œ What Is It?

The Best Time to Buy and Sell Stock problem involves finding the maximum profit you can achieve by buying and selling a stock. You are given an array where each element represents the stock price on a given day. You can only complete one transaction (buy one and sell one share).

๐Ÿงฑ Pattern Template

Greedy Algorithm

class Solution {
    public int maxProfit(int[] prices) {
        int minPrice = Integer.MAX_VALUE;
        int maxProfit = 0;

        for (int price : prices) {
            if (price < minPrice) {
                minPrice = price; // Update the minimum price
            } else if (price - minPrice > maxProfit) {
                maxProfit = price - minPrice; // Update the maximum profit
            }
        }

        return maxProfit;
    }
}

๐Ÿ“Š Time Complexity

โœ… Use Cases

๐Ÿ“˜ Common LeetCode Problems

๐Ÿงช Example

Input: prices = [7, 1, 5, 3, 6, 4]
Output: 5

Explanation:
- Buy on day 2 (price = 1) and sell on day 5 (price = 6).
- Profit = 6 - 1 = 5.

๐Ÿ’ก Pro Tips