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

LeetCode--Best Time to Buy and Sell Stock(最大利润)Python

2017-11-23 15:39 507 查看
题目:

给定一个数组,第i个位置表示第i天的价格,要求只能完成一组交易(买入一次+卖出一次),求出最大利润。

解题思路:

对数组进行遍历,保存当前的最小买入价格和当前的最大利润,遍历结束后,返回最终的最大利润即可。

代码(python):

class Solution(object):
def maxProfit(self, prices):
"""
:type prices: List[int]
:rtype: int
"""
n = len(prices)
if n==0 or n==1:
return 0
min0 = prices[0]
max0 = 0
for i in range(n):
if prices[i]<min0:
min0 = prices[i]
continue
if prices[i]>=min0:
if prices[i]-min0>max0:
max0 = prices[i]-min0
continue
else:
continue
return max0
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: