您的位置:首页 > 编程语言 > Python开发

leetcode之Best Time to Buy and Sell Stock

2016-02-03 22:58 836 查看
这题要求的是最多只完成一次交易,所以就回到了最大子数组和的问题上了。将所有的升降列出来,然后1次交易求出最大值。借鉴了别人写的屌屌的代码。代码如下:
class Solution(object):
def maxProfit(self, prices):
"""
:type prices: List[int]
:rtype: int
"""
if len(prices) <= 1:
return 0
list1 = []
for i in range(len(prices) - 1):
list1.append(prices[i + 1] - prices[i])
if len(list1) == 1:
return [list1[0], 0][list1[0] < 0]
for i in range(1, len(list1)):
list1[i] = max(list1[i], list1[i] + list1[i - 1])
return [max(list1), 0][max(list1) < 0]
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息