121. Best Time to Buy and Sell Stock

121. Best Time to Buy and Sell Stock

0. 參考文獻

序號 文獻
1 [LeetCode:Best Time to Buy and Sell Stock I II III]

1. 題目

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

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.this

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

Example 1:element

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

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

2. 思路

本題可使用動態規劃的方式解決。設dp[i]是0-i天的時候獲取的最大利潤,則dp[i] 的遞推關係是:io

  1. 若是prices[i] 減去以前的區間裏面的最小值大於 dp[i-1] ,則dp[i]的值等於這個值。
  2. 不然dp[i] 的值等於dp[i-1]

所以,最大的利率就是dp[0] dp[1] …. dp[n]的最大值table

3. 實現

class Solution(object):
    def maxProfit(self, prices):
        """
        :type prices: List[int]
        :rtype: int
        """
        # dp[i] = max{dp[i-1],p[i] - minprice }
        dp = [ 0 ] * len(prices)
        l = len(prices)
        if l <= 1 :return 0
        min_prices = 0 
        #ret = 0 
        dp[0] = -prices[0]
        dp[1] = prices[1] - prices[0]
        min_prices = min(prices[1],prices[0])
        for i in range(2,l):
            min_prices = min(min_prices,prices[i-1])
            dp[i] = max(dp[i-1],prices[i] - min_prices)
            
        ret = 0 
        for e in dp:
            ret = max(ret,e)
        return ret
相關文章
相關標籤/搜索