专注于 JetBrains IDEA 全家桶,永久激活,教程
持续更新 PyCharm,IDEA,WebStorm,PhpStorm,DataGrip,RubyMine,CLion,AppCode 永久激活教程

leetcode 买卖股票 golang

1、只能有一次买入卖出的机会 LeetCode121
第几次卖出能得到的最大值是 前一次卖出得到的最大值和这次卖出得到的减去这次之前的最小值两者之间的大值。
max[i] = max(max[i-1], price[i]-minPrice)

func maxProfit1_1(prices []int) int {
    minPrice := prices[0]
    dp := make([]int, len(prices))
    dp[0] = 0
    for i := 1; i < len(prices); i++ {
        dp[i] = myMax(dp[i-1], prices[i]-minPrice)
        minPrice = myMin(minPrice, prices[i])
    }
    return dp[len(prices)-1]
}

也可以不使用数组,直接变量保存当前最大值即可。

func maxProfit(prices []int) int {
    maxProfit := 0
    minPrice := prices[0]
    for i := 1; i < len(prices); i++ {
        maxProfit = myMax(maxProfit, prices[i]-minPrice)
        minPrice = myMin(minPrice, prices[i])
    }
    return maxProfit
}

![](https://user-gold-cdn.xitu.io/2019/9/6/16d05ed51ed836f7?w=660&h=136&f=png&s=24046)

func myMax(a, b int) int {
    if a > b {
        return a
    } else {
        return b
    }
}

func myMin(a, b int) int {
    if a > b {
        return b
    } else {
        return a
    }
}

2、可以多次买入卖出 LeetCode122

65_1.png贪心,每次只要比上次有增长,就可以卖出。

func maxProfit(prices []int) int {
    maxProfit := 0
    for i := 0; i < len(prices)-1; i++ {
        if prices[i] < prices[i+1] {
            maxProfit += prices[i+1] - prices[i]
        } else {
            continue
        }
    }
    return maxProfit
}

文章永久链接:https://tech.souyunku.com/45196

未经允许不得转载:搜云库技术团队 » leetcode 买卖股票 golang

JetBrains 全家桶,激活、破解、教程

提供 JetBrains 全家桶激活码、注册码、破解补丁下载及详细激活教程,支持 IntelliJ IDEA、PyCharm、WebStorm 等工具的永久激活。无论是破解教程,还是最新激活码,均可免费获得,帮助开发者解决常见激活问题,确保轻松破解并快速使用 JetBrains 软件。获取免费的破解补丁和激活码,快速解决激活难题,全面覆盖 2024/2025 版本!

联系我们联系我们