序號 | 文獻 |
---|---|
1 | [LeetCode:Best Time to Buy and Sell Stock I II III] |
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.
本題可使用動態規劃的方式解決。設dp[i]是0-i天的時候獲取的最大利潤,則dp[i] 的遞推關係是:io
所以,最大的利率就是dp[0] dp[1] …. dp[n]的最大值table
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