LeetCode - #123 买卖股票的最佳时机 III

持续创作,加速成长!这是我参与「掘金日新计划 · 6 月更文挑战」的第34天,点击查看活动详情

前言

我们社区陆续会将顾毅(Netflix 增长黑客,《iOS 面试之道》作者,ACE 职业健身教练。)的 Swift 算法题题解整理为文字版以方便大家学习与阅读。

LeetCode 算法到目前我们已经更新到 122 期,我们会保持更新时间和进度(周一、周三、周五早上 9:00 发布),每期的内容不多,我们希望大家可以在上班路上阅读,长久积累会有很大提升。

不积跬步,无以至千里;不积小流,无以成江海,Swift社区 伴你前行。如果大家有建议和意见欢迎在文末留言,我们会尽力满足大家的需求。

难度水平:困难

1. 描述

给定一个数组,它的第 i 个元素是一支给定的股票在第 i 天的价格。

设计一个算法来计算你所能获取的最大利润。你最多可以完成 两笔 交易。

注意: 你不能同时参与多笔交易(你必须在再次购买前出售掉之前的股票)。

2. 示例

示例 1

输入:prices = [3,3,5,0,0,3,1,4]
输出:6
解释:在第 4 天(股票价格 = 0)的时候买入,在第 6 天(股票价格 = 3)的时候卖出,这笔交易所能获得利润 = 3-0 = 3 。
     随后,在第 7 天(股票价格 = 1)的时候买入,在第 8 天 (股票价格 = 4)的时候卖出,这笔交易所能获得利润 = 4-1 = 3 。

示例 2

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

示例 3

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

示例 3

输入:prices = [1]
输出:0

约束条件:

  • 1 <= prices.length <= 10^5
  • 0 <= prices[i] <= 10^5

3. 答案

class BestTimeBuySellStockIII {
    func maxProfit(_ prices: [Int]) -> Int {
        guard prices.count > 0 else {
            return 0
        }
        
        var maxProfit = 0
        var finalMaxProfit = 0
        var maxProfitLeft = [Int]()
        var low = prices.first!
        var high = prices.last!
        
        for price in prices {
            maxProfit = max(price - low, maxProfit)
            low = min(price, low)
            maxProfitLeft.append(maxProfit)
        }
        
        maxProfit = 0
        
        for i in (0..<prices.count).reversed() {
            let price = prices[i]
            maxProfit = max(high - price, maxProfit)
            high = max(price, high)
            finalMaxProfit = max(finalMaxProfit, maxProfit + maxProfitLeft[i])
        }
        
        return finalMaxProfit
    }
}
  • 主要思想:动态规划,找到 [0,i][i, count - 1] 的和最大的点。
  • 时间复杂度: O(n)
  • 空间复杂度: O(n)

该算法题解的仓库:LeetCode-Swift

点击前往 LeetCode 练习

关于我们

我们是由 Swift 爱好者共同维护,我们会分享以 Swift 实战、SwiftUI、Swift 基础为核心的技术内容,也整理收集优秀的学习资料。

猜你喜欢

转载自juejin.im/post/7114607061886828558
今日推荐