1 Star 0 Fork 3

buelev / leetcode

forked from 光花梗虎耳草 / leetcode 
加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
README.md 3.40 KB
一键复制 编辑 原始数据 按行查看 历史

714. 买卖股票的最佳时机含手续费

English Version

题目描述

给定一个整数数组 prices,其中第 i 个元素代表了第 i 天的股票价格 ;非负整数 fee 代表了交易股票的手续费用。

你可以无限次地完成交易,但是你每笔交易都需要付手续费。如果你已经购买了一个股票,在卖出它之前你就不能再继续购买股票了。

返回获得利润的最大值。

注意:这里的一笔交易指买入持有并卖出股票的整个过程,每笔交易你只需要为支付一次手续费。

示例 1:

输入: prices = [1, 3, 2, 8, 4, 9], fee = 2
输出: 8
解释: 能够达到的最大利润:  
在此处买入 prices[0] = 1
在此处卖出 prices[3] = 8
在此处买入 prices[4] = 4
在此处卖出 prices[5] = 9
总利润: ((8 - 1) - 2) + ((9 - 4) - 2) = 8.

注意:

  • 0 < prices.length <= 50000.
  • 0 < prices[i] < 50000.
  • 0 <= fee < 50000.

解法

动态规划法。

设 f1 表示当天持有股票的最大利润,f2 表示当天没持有股票的最大利润。

初始第 1 天结束时,f1 = -prices[0]f2 = 0

从第 2 天开始,当天结束时:

  • 若持有,则可能是前一天持有,今天继续持有;也可能前一天没持有,今天买入,f1 = max(f1, f2 - price)
  • 若没持有,则可能是前一天持有,今天卖出;也可能是前一天没没有,今天继续没持有,f2 = max(f2, f1 + price - fee)

最后返回 f2 即可。

Python3

class Solution:
    def maxProfit(self, prices: List[int], fee: int) -> int:
        # 持有,没持有
        f1, f2 = -prices[0], 0
        for price in prices[1:]:
            f1 = max(f1, f2 - price)
            f2 = max(f2, f1 + price - fee)
        return f2

Java

class Solution {
    public int maxProfit(int[] prices, int fee) {
        int f1 = -prices[0], f2 = 0;
        for (int i = 1; i < prices.length; ++i) {
            f1 = Math.max(f1, f2 - prices[i]);
            f2 = Math.max(f2, f1 + prices[i] - fee);
        }
        return f2;
    }
}

C++

class Solution {
public:
    int maxProfit(vector<int>& prices, int fee) {
        int f1 = -prices[0], f2 = 0;
        for (int i = 1; i < prices.size(); ++i) {
            f1 = max(f1, f2 - prices[i]);
            f2 = max(f2, f1 + prices[i] - fee);
        }
        return f2;
    }
};

Go

func maxProfit(prices []int, fee int) int {
	f1, f2 := -prices[0], 0
	for i := 1; i < len(prices); i++ {
		f1 = max(f1, f2-prices[i])
		f2 = max(f2, f1+prices[i]-fee)
	}
	return f2
}

func max(a, b int) int {
	if a > b {
		return a
	}
	return b
}

...

马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/buelev/leetcode.git
git@gitee.com:buelev/leetcode.git
buelev
leetcode
leetcode
main

搜索帮助

344bd9b3 5694891 D2dac590 5694891