121. Best Time to Buy and Sell Stock

안창범·2023년 8월 23일
0

문제

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

해결 방법

  • 지금 물건을 샀을 때, 미래에 언제 팔지를 결정하는 식으로 접근하는 것이 아닌 지금 물건을 팔 때, 이전에 나왔던 값들 중에 가장 싼 값에 샀다면 이득이 얼마일지 계산하면 쉽게 해결할 수 있음

코드

class Solution {
    public int maxProfit(int[] prices) {
        int answer = 0;
        int min = prices[0];

        for (int i = 1 ; i < prices.length ; i ++) {
            min = Math.min(min, prices[i]);
            answer = Math.max(answer, prices[i] - min);
        }

        return answer;
    }
}

결과

0개의 댓글

관련 채용 정보