가장 쌀 때 사서 비싸게 파는 경우를 찾는 문제이므로, 파는 것을 기준으로 순회 하였으면,
값을 체크해서 가장 낮은 금액일 경우 해당 금액을 사는 날로 변경하였다.

시간의 개념이 들어가므로 파는 날짜보다 사는 날짜가 이전에 있어야 하기 때문에 무작정 최소 값을 사는 기준으로 하는 것이 아니라 파는 날짜를 순회해서 기준이 되는 날짜를 찾았다.

public class Solution {  
    public int maxProfit(int[] prices) {  
        int maxProfit = 0;  
        int minPrice = prices[0];  
        int buy = 0;  
  
        // 매일 파는 값을 체크, 사는 지점은 값(minPrice)이 가장 낮은 지점일 때  
        for(int sell = 1; sell < prices.length; sell++){  
            int buyPrice = prices[buy];  
            int sellPrice = prices[sell];  
            int curProfit = sellPrice - buyPrice;  
  
            // 최저가일 경우 구매점으로 변경  
            if(sellPrice < minPrice){  
                buy = sell;  
                minPrice = sellPrice;  
                continue;  
            }  
  
            maxProfit = Math.max(curProfit, maxProfit);  
        }  
  
        return maxProfit;  
    }  
}

+ Recent posts