天天看點

leetcode(18)-----Best Time to Buy and Sell Stock

121. 買賣股票的最佳時機

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 1:

Input: [,,,,,]
Output: 
Explanation: Buy on day  (price = ) and sell on day  (price = ), profit = - = 
             Not - = , 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.
           

Python代碼實作:

1.暴力窮舉

一些有時間限制的可能實作不了

class Solution:
    def maxProfit(self, prices):
        maxpro = 
        for i in range(, len(prices)):
            min = prices[i]
            for i in range(i+, len(prices)):
                pro = prices[i] - min
                if pro > maxpro:
                    maxpro = pro
        return maxpro
           

2.分治法

先把最大內插補點設為0,第一個數設為最小數,然後周遊下一個數是否比最小數小,如果是就将最小數替換更新,如果不是,再判斷這個數減去之前的最小數之後 是否大于最大內插補點,如果是就将最大內插補點替換更新掉,如果不是就開始判斷下一個數,如此循環下去,找到最大內插補點。

class Solution:
    def maxProfit(self, prices):
        if prices ==None or len(prices)==:
            return 
        maxpro = 
        min = prices[]
        for i in range(, len(prices)):
            if min > prices[i]:
                min = prices[i]
            elif prices[i] - min > maxpro:
                maxpro = prices[i] - min
        return maxpro
           

121. 買賣股票的最佳時機 ||