问题描述
给定一个列表,列表中每一个元素表示特定日期的股票价格。计算并返回买卖股票的最大利润,股票只能买卖一次。
测试样例
# 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