[DP - Multidimensional, Medium] Best Time to Buy and Sell Stock with Transaction Fee

송재호·2025년 4월 3일
0

https://leetcode.com/problems/best-time-to-buy-and-sell-stock-with-transaction-fee/description/?envType=study-plan-v2&envId=leetcode-75

산 경우와 판 경우의 max를 계속 누적해가면 되겠다.

수수료는 사거나 팔 때 한 번만 내면 된다고 했으니 일관성만 있게 살 때 또는 팔 때 fee를 빼주면 되겠다. 팔 때 수수료를 매기는 걸로 해보자.

처음 세팅

  • sell: 0 (팔게없음)
  • buy: -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;
    }
}
profile
식지 않는 감자

0개의 댓글