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

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

func maxProfit(prices \[\]int) int {

result := 0 //利润总和

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

if pricesi-pricesi-1 > 0 {

result = result + (pricesi - pricesi-1)

}

}

return result

}

//55. 跳跃游戏

func canJump(nums \[\]int) bool {

step := 0 //步数

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

if i+numsi > step {

step = i + numsi

}

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+numsi > next {

next = i + numsi

}

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

}

相关推荐
Jerry1 小时前
LeetCode 459. 重复的子字符串
算法
海石4 小时前
1500分的题目,确实有实力,不过还是我略胜一筹
算法·leetcode
海石4 小时前
【记忆化搜索】条条大路通AC,走好适合你的那一条,走到后再考虑走得快
算法·leetcode
Jerry6 小时前
LeetCode 151. 反转字符串中的单词
算法
gugucoding7 小时前
31. 【C语言】堆栈与队列的实现
c语言·开发语言·数据结构·链表
我叫黑大帅7 小时前
别再手动写 updated_at了,这坑我踩过
后端·面试·go
ChaoZiLL8 小时前
我的数据结构3——链表(link list)
数据结构·链表
a1117768 小时前
LM 算法迭代过程动画演示(SLAM)
算法
头茬韭菜9 小时前
Context 的生死抉择:四层压缩、截断算法与 Session Memory
算法·ai
Jerry9 小时前
LeetCode 541. 反转字符串 II
算法