剑指 Offer 63. 股票的最大利润
题目:假设把某股票的价格按照时间先后顺序存储在数组中,请问买卖该股票一次可能获得的最大利润是多少? 中等
方法:动态规划 时间复杂度O(n) 空间复杂度O(1)
动态规划,dp[i]记录前i天的最大利润
动态记录前i天的买进最低花费,用新的一天的卖出价格减去最低花费,与dp[i-1]比较,取大的
def maxProfit(prices): """ :type prices: List[int] :rtype: int """ cost,profit = float('inf'),0 for price in prices: cost = min(cost,price) profit = max(profit,price - cost) return profit

浙公网安备 33010602011771号