【LeetCode】121. 买卖股票的最佳时机

leetcode

 

Golang 实现思路与代码

根据搜索结果中的 ​一次遍历法​ 和 ​动态维护最小价格策略​,以下是时间复杂度为 O(n)、空间复杂度为 O(1) 的 Golang 实现方案:

func maxProfit(prices []int) int {
    minPrice := math.MaxInt32 // 初始化最小价格为一个极大值
    maxProfit := 0            // 初始化最大利润为0

    for _, price := range prices {
        if price < minPrice {
            // 更新历史最低价
            minPrice = price
        } else if profit := price - minPrice; profit > maxProfit {
            // 计算当前价格与历史最低价的利润,更新最大利润
            maxProfit = profit
        }
    }
    return maxProfit
}

 


代码解析与关键点

  1. 核心逻辑​:

    • 维护最小价格:通过遍历不断更新 minPrice,记录到当前为止的最低买入价。
    • 动态计算利润:若当前价格高于 minPrice,计算利润并更新 maxProfit
  2. 边界处理

    • 空数组或单元素数组:若输入数组长度小于2,maxProfit 保持初始值0,直接返回。
    • 全递减序列​:minPrice 始终更新为最新价格,利润无法为正,返回0。
  3. 时间复杂度优化​:

    • 仅需一次遍历,避免暴力双循环的 O(n²) 复杂度,适用于大数组(如提示中的长度 ≤1e5)。

测试用例验证

func main() {
    fmt.Println(maxProfit([]int{7,1,5,3,6,4})) // 输出:5(符合示例1)
    fmt.Println(maxProfit([]int{7,6,4,3,1}))   // 输出:0(符合示例2)
    fmt.Println(maxProfit([]int{2,4,1}))        // 输出:2(最低价1,最高价4)
    fmt.Println(maxProfit([]int{3}))            // 输出:0(无法交易)
}

 


复杂度分析

维度说明
时间复杂度 O(n),仅需一次遍历数组。
空间复杂度 O(1),仅使用常数级变量存储中间值。

扩展思考

  • 多次买卖问题​(如 LeetCode 122):若允许无限次交易,可改用 ​贪心法 累加所有上升区间的利润。
  • 动态规划解法:适用于更复杂的交易限制(如含冷冻期、手续费等),需定义状态转移方程。
posted @ 2025-03-19 21:02  云隙之间  阅读(17)  评论(0)    收藏  举报