DEV Community

Debesh P.
Debesh P.

Posted on

121. Best Time to Buy and Sell Stock | LeetCode | Top Interview 150 | Coding Questions

Problem Link

https://leetcode.com/problems/best-time-to-buy-and-sell-stock/


leetcode 121


Solution

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

        for(int i=0; i<n; i++) {
            minPrice = Math.min(minPrice, prices[i]);
            int profit = prices[i] - minPrice;
            maxPrice = Math.max(maxPrice, profit);
        }

        return maxPrice;
    }
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)