[Leetcode] 121. Best Time to Buy and Sell Stock

whitehousechef·2025년 5월 18일

https://leetcode.com/problems/best-time-to-buy-and-sell-stock/description/?envType=study-plan-v2&envId=top-interview-150

intiial

very straightword q but dont get the min() value cuz if we have 5,699,1,3 then we are gonna skip the 5 699 profit. Instead, once we see a smaller value that we can buy our stock at, we update count. Else everytime we see a bigger value than this count, we update answer with the profit

sol

class Solution {
    public int maxProfit(int[] prices) {
        // 5,699,1,3
        int check=prices[0];
        int ans=0;
        for(int i =1;i<prices.length;i++){
            if(prices[i]<check){
                check=prices[i];
            } else{
                ans=Math.max(ans,prices[i]-check);
            }
        }
        return ans;
    }
}

complexity

n time
1 space

0개의 댓글