leetcode

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

누누01 2024. 3. 28. 06:30
728x90

 

 

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

 


 

문제

정수배열 price[] 가 주어질 때, price[i] 은 i 날에 물건의 값이다.

이 때 물건을 사는 날과 파는 날을 정해 가장 높은 이익을 구하는 문제이다.

이익을 낼 수 없을 때는 0을 반환해야 한다.

 

풀이

최소 가격을 의미하는 변수만 가지고 있으면 쉽게 풀 수 있다고 생각하였다.

따라서 최대 이익을 의미하는 max 변수의 초기값을 0으로 놓고, 최소 가격을 의미하는 minNum 을 계속 업데이트 해주며 max 값을 구한다.

class Solution {
    public int maxProfit(int[] prices) {
        int max = 0;
        int minNum = Integer.MAX_VALUE;
        for (int price : prices) {
            if (minNum > price) {
                minNum = price;
            } else {
                max = Integer.max(max, price - minNum);
            }
        }

        return max;
    }
}