[Leetcode] 122. Best Time to Buy and Sell Stock II

whitehousechef·2025년 5월 18일

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

initial

actually i thought maybe we can just buy at the lowest using same logic from the easy version of LC q and sell at a highest maximum point. Because we can only hold 1 share, this logic is just adding all upward trends.

initial sol, i have set count as 1000k cuz we need to update check variable again in the if statement by updating it with prices[i]. If it is small, it cant be updated.

class Solution {
    public int maxProfit(int[] prices) {
        int ans =0;
        int check=prices[0];
        int i =1;
        while(i<prices.length){
            if(prices[i]<check){
                check=prices[i];
                i+=1;
            } else{
                int tmp=0;
                while (i<prices.length && tmp<prices[i]){
                    tmp=prices[i];
                    i+=1;
                }
                ans+=(tmp-check);
                check=10000000;
            }
        }
        return ans;

    }
}

sol

just add upwards trend

class Solution {
    public int maxProfit(int[] prices) {
        int maxProfit = 0;
        for (int i = 1; i < prices.length; i++) {
            if (prices[i] > prices[i - 1]) {
                maxProfit += prices[i] - prices[i - 1];
            }
        }
        return maxProfit;
    }
}

complexity

n time
1 space

0개의 댓글