LeetCode 121. The Best Time to Buy and Sell Stock (Java)

Kim Yongbin·2024년 4월 14일
post-thumbnail

문제

Best Time to Buy and Sell Stock - LeetCode

Code

class Solution {
    public int maxProfit(int[] prices) {
        int minPrice = 10000;
        int maxProfit = 0;

        for (int price: prices){
            if (minPrice > price){
                minPrice = price;
            } else {
                maxProfit = Math.max(maxProfit, price - minPrice);
            }
        }
        return maxProfit;
    }
}

  1. 가장 싸게 사서 가장 비싸게 팔아야 최대 이익을 얻을 수 있다.
  2. 앞에서부터 탐색하면서 최소 가격을 갱신하거나, 현재 가격에 팔았을 때의 이득을 비교하였다.
profile
반박 시 여러분의 말이 맞습니다.

0개의 댓글