动态规划

Mr.Clark大约 1 分钟

动态规划

动态规划是算法与数据结构的重难点之一,其包含了「分治思想」、「空间换时间」、「最优解」等多种基石算法思想

股票最大利润

假设把某股票的价格按照时间先后顺序存储在数组中,请问买卖该股票一次可能获得的最大利润是多少?

输入: [7,1,5,3,6,4]
输出: 5
解释: 在第 2 天(股票价格 = 1)的时候买入,在第 5 天(股票价格 = 6)的时候卖出,最大利润 = 6-1 = 5  
     注意利润不能是 7-1 = 6, 因为卖出价格需要大于买入价格。
 

输入: [7,6,4,3,1]
输出: 0
解释: 在这种情况下, 没有交易完成, 所以最大利润为 0。
 stockprices=[7,1,5,3,6,4]

#暴力解法
def maxProfit(prices):
    """
    :type prices: List[int]
    :rtype: int
    """
    if len(prices)<=1:
        return 0
    maxres=0
    n=len(prices)
    for i in range(n-1):
        for j in range(i+1,n):
            if maxres<prices[j]-prices[i]:
                maxres=prices[j]-prices[i]
    return maxres

print(maxProfit(stockprices))

#动态规划
def maxProfit2(prices):
    """
    :type prices: List[int]
    :rtype: int
    """
    if len(prices)<=1:
        return 0
    cost,profit=prices[0],0
    for price in prices[1:]:  #买入股票 T+1天后才能卖
        cost=min(cost,price)     
        profit=max(profit,price-cost)  
    return profit
print(maxProfit2(stockprices))

上次编辑于:
贡献者: Chuang Ke