LeetCode知识点总结 - 714

该篇文章讨论了解题网站LeetCode上的股票买卖问题,涉及在考虑交易费用的情况下,如何通过贪婪算法求得最大利润。算法核心是计算买入价buy和卖出价sell,每次更新时,买入价等于当天价格和当前最大卖出价之差,卖出价等于买入价加上当天价格再减去交易费。
摘要由CSDN通过智能技术生成

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

考点难度
GreedyEasy
题目

You are given an array prices where prices[i] is the price of a given stock on the ith day, and an integer fee representing a transaction fee.

Find the maximum profit you can achieve. You may complete as many transactions as you like, but you need to pay the transaction fee for each transaction.

思路

buy = max(buy, sell - price)
sell = max(sell, buy + price - fee)
iterate一遍,sell是max profit

答案
class Solution(object):
    def maxProfit(self, prices, fee):
        buy = float('-inf')
        sell = 0

        for price in prices:
            buy = max(buy, sell - price)
            sell = max(sell, buy + price - fee)    
  • 7
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值