题目描述:假设有一个数组,它的第i个元素是一支给定的股票在第i天的价格。如果你最多只允许完成一次交易(例如,一次买卖股票),设计一个算法来找出最大利润。
样例:给出一个数组样例 [3,2,3,1,2], 返回 1
换一个角度来思考这个问题,最大利润实际上就是每天的交易价格,减去上一天的价格所构成的这个数组的最大子数组。
有关最大子数组的解法已经讲过(详见:点击打开链接),不明白的请回看。
所以,是一样的东西了,只不过需要求取一个差值。
代码如下:
class Solution:
"""
@param prices: Given an integer array
@return: Maximum profit
"""
def maxProfit(self, prices):
if len(prices) <= 1:
return 0
n = len(prices)
sum_value = 0
max_value = 0
for i in range(1, n):
sum_value += prices[i] - prices[i - 1]
max_value = max(max_value, sum_value)
sum_value = max(0, sum_value)
return max_value
# write your code here