'示例 1: '输入: [7,1,5,3,6,4] '输出:5 '解释:在第 2 天(股票价格 = 1)的时候买入,在第 5 天(股票价格 = 6)的时候卖出,最大利润 = 6-1 = 5 。注意利润不能是 7-1 = 6, 因为卖出价格需要大于买入价格;同时,你不能在买入前卖出股票。 ' '示例 2: '输入: prices = [7,6,4,3,1] '输出:0 '解释:在这种情况下, 没有交易完成, 所以最大利润为 0 Sub d32_动态规划_买卖股票的最佳时机() prices = Array(7, 1, 5, 3, 6, 4) Dim dp(1) dp(0) = -prices(0) dp(1) = 0 For i = 1 To UBound(prices) dp(0) = Application.Max(dp(0), -prices(i - 1)) dp(1) = Application.Max(dp(1), dp(0) + prices(i - 1)) Next Debug.Print (dp(1)) End Sub Sub d32_动态规划_买卖股票的最佳时机2() prices = Array(7, 1, 5, 3, 6, 4) res = maxProfit(prices) Debug.Print (res) End Sub Public Function maxProfit(prices) If UBound(prices) = 0 Then maxProfit = 0: Exit Function length_ = UBound(prices) + 1 Dim dp() ReDim dp(length_, 1) result = 0 dp(0, 0) = -prices(0) dp(0, 1) = 0 For i = 1 To UBound(prices) dp(i, 0) = Application.Max(dp(i - 1, 0), -prices(i)) dp(i, 1) = Application.Max(dp(i - 1, 0) + prices(i), dp(i - 1, 1)) Next maxProfit = dp(length_ - 1, 1) End Function
标签:买卖,Sub,UBound,maxProfit,Application,最佳时机,prices,动态,dp From: https://www.cnblogs.com/eyunkeji/p/16972841.html