Skip to content

· 1 min read

Blind 75 - Best Time To Buy And Sell Stock

Make sure the left pointer is always the lowest yet. Keep checking the difference between left and right. And return max.

Link

Learning From

NeetCode

Asked at

Source

Video

https://youtu.be/7KHKFqLPMbs

Problem and Constraints

Given an array of stock prices. What’s the maximum profile that one can get?

All Approaches and Explanations in English

O(n) time complexity. O(1) space complexity

Make sure the left pointer is always the lowest yet. Keep checking the difference between left and right. And return max.

Code, if any

class Solution {
    public int maxProfit(int[] prices) {
        int left = 0;
        int right = 1;
        int maxYet = 0;
        while(right < prices.length){
            int leftItem = prices[left];
            int rightItem = prices[right];
            if(rightItem < leftItem){
                left = right;
                right = right+1;
                continue;
            }
            maxYet = Math.max(maxYet, rightItem - leftItem);
            right++;
        }
        return maxYet;
    }
}

Get new posts by email

No spam. Unsubscribe anytime. Or grab the RSS feed.

Mailto-based for now. ButtonDown / ConvertKit can replace this form later.


Comments lazy-load on scroll. Prefer GitHub? Giscus activates once PUBLIC_GISCUS_* env vars are set (see Giscus.astro).

Index

Index

Back to Blog