【LeetCode】股票的最大盈利值(python)

LeetCode原题:

题号:121. Best Time to Buy and Sell Stock

链接:https://leetcode.com/problems/best-time-to-buy-and-sell-stock/description/

《剑指offer》题目描述:

给定一个整形数组,其中的第i个元素代表股票第i天的价格。在一开始,你手里有足够的钱,但没有股票。你仅有一次买股票和一次卖股票的机会(每次只能买/卖1股),或者不买不卖。输出你可能的最大盈利值。尽量降低程序的时间复杂度。

样例1:

[7, 1, 5, 3, 6, 4],在价格为1的时候买入,在价格为6的时候卖出,可以得到最大盈利值为5。(5 = 6 - 1)

 思路

题目的实质是:求连续子数组中差值和最大的那个差值和。 【动态规划】

class Solution(object):
    def maxProfit(self, prices):
        """
        :type prices: List[int]
        :rtype: int
        """
        if not prices:
            return 0
        cur_diff = 0
        maxn = 0
        for i in range(1,len(prices)):
            cur_diff = max(cur_diff+prices[i]-prices[i-1],0)
            maxn = max(cur_diff,maxn)
        return maxn

 


版权声明:本文为yingzoe原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。