算法训练营day28(补), 贪心算法2

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

func maxProfit(prices []int) int {

result := 0 //利润总和

for i := 1; i < len(prices); i++ {

if prices[i]-prices[i-1] > 0 {

result = result + (prices[i] - prices[i-1])

}

}

return result

}

//55. 跳跃游戏

func canJump(nums []int) bool {

step := 0 //步数

for i := 0; i <= step; i++ {

if i+nums[i] > step {

step = i + nums[i]

}

if step >= len(nums)-1 {

return true

}

}

return false

}

//45. 跳跃游戏 II

func jump(nums []int) int {

cur := 0 //当前指针

next := 0 //下一个指针

result := 0 //步骤统计

for i := 0; i < len(nums); i++ {

if i+nums[i] > next {

next = i + nums[i]

}

if i == cur && cur != len(nums)-1 {

result++

cur = next

if cur >= len(nums)-1 {

return result

}

} else if i == cur {

return result

}

}

return result

}

相关推荐
小白程序员成长日记1 小时前
2025.12.03 力扣每日一题
算法·leetcode·职场和发展
元亓亓亓1 小时前
LeetCode热题100--20. 有效的括号--简单
linux·算法·leetcode
熊猫_豆豆1 小时前
LeetCode 49.字母异位组合 C++解法
数据结构·算法·leetcode
ModestCoder_2 小时前
强化学习 Policy 的 Tracking 能力全解析,以Legged_gym为例解说Policy的训练流程
人工智能·算法·自然语言处理·机器人·具身智能
光头闪亮亮2 小时前
Golang开发自动加载COM扫码枪进行一维码、二维码扫码与解码
go
小白程序员成长日记2 小时前
2025.12.02 力扣每日一题
数据结构·算法·leetcode
永远都不秃头的程序员(互关)3 小时前
在vscodeC语言多文件编译实战指南
c语言·数据结构·算法
wen-pan3 小时前
Go 语言 GMP 调度模型深度解析
开发语言·go
立志成为大牛的小牛3 小时前
数据结构——五十三、处理冲突的方法——拉链法(王道408)
数据结构·学习·考研·算法
吃着火锅x唱着歌3 小时前
LeetCode 3583.统计特殊三元组
算法·leetcode·职场和发展