본문 바로가기

Algorithm

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

문제해석

각 i번째 날의 주가가 들어있는 배열 prices가 주어졌을 때

가장 큰 수익이 날 수 있는 값을 반환하기

주식은 무조건 산 이후 날만 판매가 가능함

 

정답 예

public int maxProfit(int[] prices) {
    int length = prices.length;
    if (length == 1) {
        return 0;
    }

    int min = prices[0];
    int maxProfit = 0;

    for (int i = 1; i < length; i++) {
        int price = prices[i];

        // 작은 값 저장
        if (min > price) {
            min = price;
        }

        int profit = price - min;

        // 현재가로 팔았을 경우 가격 비교
        if (maxProfit < profit) {
            maxProfit = profit;
        }
    }

    return maxProfit;
}

 

참고 알고리즘

카데인 알고리즘