Leetcode 122. 买卖股票的最佳时机 II(Best Time to Buy and Sell Stock II)

Leetcode 122. 买卖股票的最佳时机 II

1 题目描述(Leetcode题目链接)

  给定一个数组,它的第 i 个元素是一支给定股票第 i 天的价格。
  设计一个算法来计算你所能获取的最大利润。你可以尽可能地完成更多的交易(多次买卖一支股票)。
  注意:你不能同时参与多笔交易(你必须在再次购买前出售掉之前的股票)。

输入: [7,1,5,3,6,4]
输出: 7
解释: 在第 2 天(股票价格 = 1)的时候买入,在第 3 天(股票价格 = 5)的时候卖出, 这笔交易所能获得利润 = 5-1 = 4 。
     随后,在第 4 天(股票价格 = 3)的时候买入,在第 5 天(股票价格 = 6)的时候卖出, 这笔交易所能获得利润 = 6-3 = 3
输入: [1,2,3,4,5]
输出: 4
解释: 在第 1 天(股票价格 = 1)的时候买入,在第 5 天 (股票价格 = 5)的时候卖出, 这笔交易所能获得利润 = 5-1 = 4 。
     注意你不能在第 1 天和第 2 天接连购买股票,之后再将它们卖出。
     因为这样属于同时参与了多笔交易,你必须在再次购买前出售掉之前的股票。

2 题解

  可以多次买卖,买之前必须卖掉,因此我们考虑这样的贪心策略:只要后一天比前一天的贵,那么我们就进行买卖。

class Solution:
    def maxProfit(self, prices: List[int]) -> int:
        if not prices:
            return 0
        retv = 0
        for i in range(1, len(prices)):
            if prices[i] > prices[i - 1]:
                retv = retv + prices[i] - prices[i - 1]
        return retv

  每一个贪心的背后都有一个动态规划,这里可以考虑第 i i i天的状态,并定义相应的 D P DP DP数组:

  1. i i i天持有股票: D P 1 [ i ] DP1[i] DP1[i]表示第 i i i天持有股票时能赚到的最大钱数;
  2. i i i天不持有股票: D P 2 [ i ] DP2[i] DP2[i]表示第 i i i天不持有股票时能赚到的最大钱数;

那么 i i i天持有股票的状态可能由两种情况得来,前一天持有股票并且今天也持有股票,前一天不持有股票并且今天买了股票,则状态转移方程为:
D P 1 [ i ] = m a x ( D P 1 [ i − 1 ] , D P 2 [ i − 1 ] − p r i c e s [ i ] ) DP1[i] = max(DP1[i-1],DP2[i-1] - prices[i]) DP1[i]=max(DP1[i1],DP2[i1]prices[i])
同理第 i i i天不持有股票的状态也由两种情况得来,前一天不持有股票并且今天也不持有股票,前一天持有股票并且今天卖了股票,则状态转移方程为:
D P 2 [ i ] = m a x ( D P 2 [ i − 1 ] , D P 1 [ i − 1 ] + p r i c e s [ i ] ) DP2[i] = max(DP2[i - 1], DP1[i - 1] + prices[i]) DP2[i]=max(DP2[i1],DP1[i1]+prices[i])
最后结果应该为最后一天不持有股票能赚的最大钱数。

class Solution:
    def maxProfit(self, prices: List[int]) -> int:
        if not prices:
            return 0
        DP1 = [0]*len(prices)  #持有股票
        DP2 = [0]*len(prices)  #不持有股票
        DP1[0] = -prices[0]
        for i in range(1, len(prices)):
            DP1[i] = max(DP1[i - 1], DP2[i - 1] - prices[i])
            DP2[i] = max(DP2[i - 1], DP1[i - 1] + prices[i])
        return DP2[-1]

你可能感兴趣的:(Leetcode,leetcode,算法)