[leetcode] Array/String (Medium) - 122. Best Time to Buy and Sell Stock II

brandon·2025년 5월 21일
0

leetcode-array/strings

목록 보기
8/20

Intuition 🤔

왜 같은 날에 사서 같은 날에 팔 수 있게 만들었을까?
사실 내가 생각했을때 이 문제는 좀 더 잘 쓰여질 수 있는거 같다.
왜 수익을 내고 다시 stock을 살때 그 수익에서 stock의 가격을 빼지 않는거지?
이해가 안되지만 그래도 문제니까...

답안

class Solution {
    public int maxProfit(int[] prices) {
        int localMinimum = prices[0]; 
        int profit = 0;

        for (int i = 1; i < prices.length; i++) {
            if (prices[i] < localMinimum) {
                localMinimum = prices[i]; 
            } else if (prices[i] > localMinimum) {
                profit += (prices[i] - localMinimum); 
                localMinimum = prices[i]; 
            }
        }

        return profit; 
    }
}
profile
everything happens for a reason

0개의 댓글