714. Best Time to Buy and Sell Stock with Transaction Fee

양성준·2025년 7월 6일

코딩테스트

목록 보기
88/102

문제

https://leetcode.com/problems/best-time-to-buy-and-sell-stock-with-transaction-fee/description/

풀이

class Solution {
    public int maxProfit(int[] prices, int fee) {
        int n = prices.length;
        int[][] dp = new int[n][2];
        dp[0][0] = 0;
        dp[0][1] = -prices[0];

        for(int i = 1; i < n; i++) {
            dp[i][0] = Math.max(dp[i-1][0], dp[i-1][1] + prices[i] - fee); // 주식을 팔았거나 안팔았거나
            dp[i][1] = Math.max(dp[i-1][1], dp[i-1][0] - prices[i]); // 주식을 샀거나 안샀거나 
        }
        return dp[n-1][0];
    }
}
  • dp[i][0]: i번째 날, 주식을 가지고 있지 않은 상태의 최대 이익
    • 전날에도 주식을 소유하지 않았을 경우 dp[i-1][0]
    • 전날까지 소유하고 있던걸 팔았을 경우 dp[i-1][1] + prices[i] - fee
  • dp[i][1]: i번째 날, 주식을 갖고 있는 상태의 최대 이익
    • 전날까지 소유하고 있었던 경우 dp[i-1][1]
    • 전날에는 소유하고 있지 않았지만, 오늘 산 경우 dp[i-1][0] - prices[i];
profile
백엔드 개발자

0개의 댓글