class Solution(object): def maxProfit(self, prices): """ :type prices: List[int] :rtype: int """ if not prices: return 0 dp = [0 for __ in range(len(prices))] minPrice = prices[0] for i in range(1, len(prices)): dp[i] = max(dp[i - 1], prices[i] - minPrice) if(minPrice > prices[i]): minPrice = prices[i] return dp[-1]
直接解法
本题由于思路比较简单,可以直接解决
1 2 3 4 5 6 7 8 9 10 11 12 13
class Solution(object): def maxProfit(self, prices): """ :type prices: List[int] :rtype: int """ if not prices : return 0 ans, money, n = 0, prices[0], len(prices) for i in range(n): ans = max(ans, prices[i]-money) money = min(prices[i], money) return ans
class Solution: # @param prices, a list of integer # @return an integer def maxProfit(self, prices): maxprofit = 0 for i in range(1, len(prices)): if prices[i] >= prices[i-1]: maxprofit += prices[i] - prices[i-1] return maxprofit
class Solution(object): def maxProfit(self, prices): """ :type prices: List[int] :rtype: int """ length = len(prices) if length==0: return 0 f1 = [0 for __ in range(length)] f2 = [0 for __ in range(length)] # 从前往后最大利润 minPrice = prices[0] for i in range(1, length): f1[i] = max(f1[i-1], prices[i]-minPrice) minPrice=min(minPrice, prices[i]) # 从后往前则是最小利润 maxPrice = prices[length-1] for i in range(length-2,-1,-1): f2[i] = max(f2[i+1], maxPrice-prices[i]) maxPrice = max(maxPrice, prices[i]) maxProfit=0 for i in range(length): if f1[i]+f2[i] > maxProfit: maxProfit = f1[i]+f2[i] return maxProfit