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.
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: [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.
2. 思路
本题可以使用动态规划的方式解决。设dp[i]是0-i天的时候获取的最大利润,则dp[i] 的递推关系是:
- 如果prices[i] 减去之前的区间里面的最小值大于 dp[i-1] ,则dp[i]的值等于这个值。
- 否则dp[i] 的值等于dp[i-1]
因此,最大的利率就是dp[0] dp[1] …. dp[n]的最大值
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
编程光~