标签:leetcode
问题:
给定一个列表,第i个元素代表股票第i天的价值,只允许买入卖出一次,求最大收益
思路:动态规划
开始没想清楚,觉着遍历一次找出最大与最小股价求差就是,后来发现脑子绣住了,买入要在买出之前。
输入为列表p1p2...pm
m[i]表示前i天的最小股价,m[i] = min(p[i], m[i-1]) i >= 1 <-- O(n)时间开销
第i天卖出的最大收益是pi - m[i-1] <-- 遍历一次O(n)求出最大值
代码:Python
class Solution: # @param prices, a list of integer # @return an integer def maxProfit(self, prices): n = len(prices) if n < 2: return 0 else: # m[i] means minimal value of stock before day i m = [0 for i in range(n)] m[0] = prices[0] for i in range(1,n): m[i] = min(prices[i], m[i-1]) ret = 0 for i in range(1, n): ret = max(ret, prices[i] - m[i-1]) return ret
本文出自 “Koala程序员” 博客,请务必保留此出处http://koala87.blog.51cto.com/8339141/1627318
leetcode解题报告:121 Best Time to Buy and Sell Stock
标签:leetcode
原文地址:http://koala87.blog.51cto.com/8339141/1627318