美文网首页
LeetCode 第714题:买卖股票的最佳时机含手续费

LeetCode 第714题:买卖股票的最佳时机含手续费

作者: 放开那个BUG | 来源:发表于2021-04-23 14:04 被阅读0次

1、前言

题目描述

2、思路

在卖出或者买入的地方使用利润扣除手续费即可

3、代码

public class SellStockWithFee {

    public int maxProfit(int[] prices, int fee) {
        int n = prices.length;
        int[][] dp = new int[n][2];

        for(int i = 0; i < n; i++){
            if(i - 1 == -1){
                dp[i][0] = 0;
                dp[i][1] = -prices[i] - fee;
                continue;
            }
            dp[i][0] = Math.max(dp[i-1][0], dp[i-1][1] + prices[i]);
            dp[i][1] = Math.max(dp[i-1][1], dp[i-1][0] - prices[i] - fee);
        }

        return dp[n - 1][0];
    }

    public static void main(String[] args) {
        int[] prices = new int[] {1, 3, 2, 8, 4, 9};
        int fee = 2;
        System.out.println(new SellStockWithFee().maxProfit(prices, fee));
    }
}

相关文章

网友评论

      本文标题:LeetCode 第714题:买卖股票的最佳时机含手续费

      本文链接:https://www.haomeiwen.com/subject/gybulltx.html