산 경우와 판 경우의 max를 계속 누적해가면 되겠다.
수수료는 사거나 팔 때 한 번만 내면 된다고 했으니 일관성만 있게 살 때 또는 팔 때 fee를 빼주면 되겠다. 팔 때 수수료를 매기는 걸로 해보자.
처음 세팅
-prices[0]
(첫 번째 것을 샀으니 해당 금액만큼 마이너스 상태)이후 prices 순회 시 i=1부터 시작하면서 두 값을 갱신
buy = Math.max(buy, sell - prices[i])
-> 주식 사는 경우sell = Math.max(sell, buy + prices[i] - fee)
-> 주식 파는 경우class Solution {
public int maxProfit(int[] prices, int fee) {
int sell = 0;
int buy = -prices[0];
for (int i=1; i<prices.length; i++) {
buy = Math.max(buy, sell - prices[i]);
sell = Math.max(sell, buy + prices[i] - fee);
}
return sell;
}
}