121. Best Time to Buy and Sell Stock@python

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 (i.e., buy one and sell one share of the stock), design an algorithm to find the maximum profit.

Note that you cannot sell a stock before you buy one.

Example:

Input: [7,1,5,3,6,4]
Output: 5
Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5.
             Not 7-1 = 6, as selling price needs to be larger than buying price.

题目地址: Best Time to Buy and Sell Stock

难度: Easy

题意: 买卖股票,最多只能买卖一次

思路:

遍历数组,找到最小的价格,并且每一个值与最小值比较,找出最大值, 如上面例子:

[7,1,5,3,6,4] --> [7,1,5,3,6,4] --> [7,1,5,3,6,4] --> 
[7,1,5,3,6,4] --> [7,1,5,3,6,4]--> [7,1,5,3,6,4]

代码:

class Solution(object):
    def maxProfit(self, prices):
        """
        :type prices: List[int]
        :rtype: int
        """
        n = len(prices)
        if n <= 1:
            return 0
        res = 0

        small = prices[0]
        for i in range(n):
            if prices[i] < small:
                small = prices[i]   # 最小值
            res = max(res, prices[i]-small)
        return res

时间复杂度: O(n)

空间复杂度: O(1)

猜你喜欢

转载自www.cnblogs.com/chimpan/p/9729067.html