剑指offer 面试63题

面试63题

题目:股票的最大利润

题:假设把某股票的价格按照时间先后顺序存储在数组中,请问买卖该股票一次可获得的最大利润是多少?例如,一只股票在某些时间节点的价格为{9,11,8,5,7,12,16,14}。

如果我们能在价格为5的时候买入并在价格为16时卖出,则能获得最大的利润为11.

 

解决代码:

# -*- coding:utf-8 -*-
class Solution():
    def maxProfit(self, prices):
        """
        :type prices: List[int]
        :rtype: int
        """
        min_price=float('inf')
        max_profit=0
        for price in prices:
            if price<min_price:
                min_price=price
            profit=price-min_price
            max_profit=max(max_profit,profit)
        return max_profit

 

posted @ 2018-06-08 17:31  Fintech带你飞  阅读(644)  评论(0编辑  收藏  举报