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

  1. 122. Best Time to Buy and Sell Stock II
    思路:极大值减去极小值,所以适合 贪心算法,把nums[x+1]-nums[x]加在一起,就得到所有极大值减去极小值之和,也就是最大利润。
class Solution:
    def maxProfit(self, prices):
        """
        :type prices: List[int]
        :rtype: int
        """
        max_interest=0
        for x in range(len(prices)-1):
            temp=prices[x+1]-prices[x]
            if temp>0:max_interest+=temp
        return max_interest
  1. 714. Best Time to Buy and Sell Stock with Transaction Fee
    【贪心算法】这道题我是 比较迷的,但想到就是钱多钱少的问题,我就明白了。
# 714. Best Time to Buy and Sell Stock with Transaction Fee
# 
class Solution:
    def maxProfit(self, prices, fee):
        """
        :type prices: List[int]
        :type fee: int
        :rtype: int
        """

        profit=0
        cur_profit=0
        min_price=prices[0]
        max_price=prices[0]

        for x in range(len(prices)):
            
            # 每次交易的 price 中,选一个最小的,最大的,直到交易条件出现
            min_price=min(min_price,prices[x])
            max_price=max(max_price, prices[x])

            cur_profit=max(cur_profit,prices[i]-min_price-fee)

            # 只要保证卖出的price,后面有个比它小 fee 的,就不会亏钱
            # 因为前面这次交易扣了 fee, 那么只要有个小fee 的,分2次
            # 就不会比一次赚的少 如:【1,5,2,8】,【1,3,2,8】
            if (max_price- prices[x] )>=fee:
                profit+=cur_profit
                cur_profit=0
                min_price=prices[x]
                max_price=prices[x]

        return profit+cur_profit



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值