Kadane算法-股票最佳买卖时间

问题描述
给定一个列表,列表中每一个元素表示特定日期的股票价格。计算并返回买卖股票的最大利润,股票只能买卖一次。

测试样例

# Input: 
[9, 11, 8, 5, 7, 10]
#Output: 
5
# 在第4天买入,第6天卖出,可以获得最大利润 5(= 10 - 5).

内容首发于微信公众号IT信息教室,如果您想学习更多AI相关的技能,欢迎搜索关注或微信扫描下方二维码关注~~

在这里插入图片描述

参考代码

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
class Solution:
    # O(n) time, O(1) space.
    # 获取收益列表(当日价格-前日价格)
    def priceToProfit(self, price):
        for idx in reversed(range(1, len(price))):
            price[idx] -= price[idx-1]
        price[0] = 0
        return price
    # O(n) time, O(1) space.
    # 最大收益及为子列表的最大和,转化为 Kadane 算法
    def getMaxProfit(self, profit):
        maxProfit = -float('inf')
        currentProfit = -float('inf')
        for idx in range(len(profit)):
            currentProfit = max(profit[idx], currentProfit + profit[idx])
            maxProfit = max(maxProfit, currentProfit)
        return maxProfit
          
# Test Program
price = [9, 11, 8, 5, 7, 10]
profit = Solution().priceToProfit(price)
maxProfit = Solution().getMaxProfit(profit)
print(maxProfit)
# 5
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值