Best Time to Buy and Sell Stock - LeetCode
题目:
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 (ie, buy one and sell one share of the stock), design an algorithm to find the maximum profit.
分析:
这道题我也选择用动态规划来做,其实也有直接遍历找上下界的做法,但是这一段时间我主要练习动态规划。。
首先假设到第i天时的最大利润为P,则第i+1天时,如果今天减去这i+1天的最小价格大于最大利润,则更新利润,否则这一天选择不做。而i=1时,我们只能选择不做或者买,而最大利润因此为0.
代码:
class Solution:
# @param prices, a list of integer
# @return an integer
def maxProfit(self, prices):
if not prices or len(prices)<2:
return 0
minprice = prices[0]
profit = 0
for i in prices:
if i < minprice:
minprice = i
profit = max(profit,i-minprice)
return profit