#Leet Code# Best Time to Buy and Sell Stock

时间:2022-09-17 18:14:42

描述:数组 A,对于 i < j, 找到最大的 A[j] - A[i]

代码:

 class Solution:
# @param prices, a list of integer
# @return an integer
def maxProfit(self, prices):
if len(prices) == 0 or len(prices) == 1:
return 0 cur_min = prices[0]
max_minus = 0 for i in range(1, len(prices)):
if prices[i] < cur_min:
cur_min = prices[i]
else:
tmp = prices[i] - cur_min
if tmp > max_minus:
max_minus = tmp return max_minus

动态规划:

设dp[i]是[0,1,2...i]区间的最大利润,则该问题的一维动态规划方程如下

dp[i+1] = max{dp[i], prices[i+1] - minprices}  ,minprices是区间[0,1,2...,i]内的最低价格

最大利润 = max{dp[0], dp[1], dp[2], ..., dp[n-1]}

其他思路:

按照股票差价构成新数组 prices[1]-prices[0], prices[2]-prices[1], prices[3]-prices[2], ..., prices[n-1]-prices[n-2],求新数组的最大子段和就是最大利润

参考地址:

http://www.cnblogs.com/TenosDoIt/p/3436457.html