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

来源:互联网 发布:詹姆斯场均数据 编辑:程序博客网 时间:2024/06/07 04:48

题目:

给定一个数组,第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

阅读全文
0 0
原创粉丝点击