Python实现"买卖股票的最佳时机"的一种方法

 给定一个数组,该数组中第i个元素是某个股票第i天的价钱

如果最多只能完成一次交易(买入股票,卖出股票),设计一个算法,可以获得最大的利润

注意:在你买入股票之前不能卖出股票

Example 1:

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.

Example 2:

Input: [7,6,4,3,1]
Output: 0
Explanation: In this case, no transaction is done, i.e. max profit = 0.

1:申明三个变量,头指针pre、尾指针tail和最大利润maxProfit,头指针指向当前访问到的数组的最小值,尾指针指向当前访问到的最大值

      访问数组prices,如果出现i-pre

      继续访问数组,如果出现i-pre>tail-pre就替换tail为i(i元素值必定大于尾指针tail值),并且替换maxProfit的值为max(maxProfit,i-pre)

def maxProfit(self, prices):
        """
        :type prices: List[int]
        :rtype: int
        """
        if len(prices)<=1:
            return 0
        pre = prices[0]
        tail = prices[0]
        maxProfit = 0
        for i in range(1,len(prices)): #从第二个元素开始访问数组
            if prices[i]-pre<0:        #替换头指针和尾指针为当前访问到的数组的最小值
                pre = prices[i]
                tail = prices[i]
            if prices[i]-pre>tail-pre:    #替换尾指针为当前访问(从最小数值开始)的最大值
                maxProfit = max(prices[i]-pre, maxProfit)     #对比此时利润和之前保存的最大利润,返回现阶段可获得的最大利润
                tail = prices[i]
        return maxProfit

2:暴力法O(n^2),错误:超出时间限制

def maxProfit(self, prices):
        """
        :type prices: List[int]
        :rtype: int
        """
        maxProfit = 0
        for i in range(len(prices)):
            for j in range(i+1,len(prices)):
                if prices[j]-prices[i]>maxProfit:
                    maxProfit = prices[j]-prices[i]
        return maxProfit

算法题来自:https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock/description/

你可能感兴趣的:(Algorithms)