LeetCode#121 Best Time to Buy and Sell Stock

问题描述

Say you have an array for which the ith element is the price of a given stock on day i.

If you were only permitted to complete at most one transaction (ie, buy one and sell one share of the stock), design an algorithm to find the maximum profit.

Example 1:

Input: [7, 1, 5, 3, 6, 4]

Output: 5

max. difference = 6-1 = 5 (not 7-1 = 6, as selling price needs to be larger than buying price)

Example 2:

Input: [7, 6, 4, 3, 1]

Output: 0

In this case, no transaction is done, i.e. max profit = 0.

补充说明:

模拟一个股票系统,给定一个列表,这个列表对应的是每日的价格,然后设计一个算法,从中找到哪一天买入,哪一天卖出能够获取最大利润。这里并不关注哪日,而是只要输出最大利润值。

方案分析

  1. 作为最简单的思路,所有人都能想到时间复杂度为O(n**2)的解决方案——遍历两次,保存最大利润值。实现没问题,但不满足leetcode的时间限定。
  2. 从时间复杂度上下手,这个问题可以转换为找到最大卖出价格和找到最小买入价格的问题。定义两个变量,表示买入价格和利润,从头开始遍历。如果第二天的价格比第一天的低,设定为买入价格;这个价格和买入价格相减,并且这个利润大于保存的利润,更新。只需要一轮就可以求得最大利润。

python实现

class Solution(object):
    def maxProfit(self, prices):
        """
        :type prices: List[int]
        :rtype: int
        """
        profit = 0
        if prices:
            buy_price = prices[0]
            for price in prices[1:]:
                buy_price = min(buy_price, price)
                profit = max(profit, price-buy_price)

        return profit

你可能感兴趣的:(LeetCode#121 Best Time to Buy and Sell Stock)