序号 | 文献 |
---|---|
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