剑指offer 面试题63. 股票的最大利润

假设把某股票的价格按照时间先后顺序存储在数组中,请问买卖该股票一次可能获得的最大利润是多少?

示例 1:

输入: [7,1,5,3,6,4]
输出: 5
解释: 在第 2 天(股票价格 = 1)的时候买入,在第 5 天(股票价格 = 6)的时候卖出,最大利润 = 6-1 = 5 。
     注意利润不能是 7-1 = 6, 因为卖出价格需要大于买入价格。
示例 2:

输入: [7,6,4,3,1]
输出: 0
解释: 在这种情况下, 没有交易完成, 所以最大利润为 0。
 

限制:

0 <= 数组长度 <= 10^5

如果不加中间那个判断,是没法过用时的,所以突然想起的限制条件让我过了这道题,方法很普通,二重循环 

class Solution(object):
    def maxProfit(self, prices):
        """
        :type prices: List[int]
        :rtype: int
        """
        maxnum = 0
        minnum = 0
        for i in range(len(prices)):
            if prices[i]<minnum:
                continue
            for j in range(i):
                if(prices[i]>prices[j]):
                    minnum = prices[j]
                    profit = prices[i]-prices[j]
                    maxnum = max(maxnum,profit)
        
        return maxnum
发布了422 篇原创文章 · 获赞 256 · 访问量 56万+

猜你喜欢

转载自blog.csdn.net/qq_32146369/article/details/104873138