[leetcode] Array/String (Easy) - 121. Best Time to Buy and Sell Stock

brandon·2025년 5월 21일
0

leetcode-array/strings

목록 보기
7/20

Intuition 🤔

최소 가격을 킵한다.
느낌대로 풀면 된다. 최솟값을 킵하고 그 숫자보다 크면 그 차이를 계속 비교해 maximum profit을 구한다.
만약 최솟값 보다 더 작은 value가 있다면 새로운 최솟값으로 정하고 그때부터 또 maximum profit을 구한다.
왜 못 풀었지...

답안

class Solution {
    public int maxProfit(int[] prices) {
        int minimum = prices[0]; 
        int profit = 0; 
        for (int i = 1; i < prices.length; i++) {
            if (prices[i] < minimum) {
                minimum = prices[i]; 
            } else {
                profit = Math.max(profit, prices[i] - minimum);
            }
        }
        return profit; 
    }
}
profile
everything happens for a reason

0개의 댓글