算法训练营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

}

相关推荐
.道阻且长.3 小时前
2.LeetCode算法习题讲解--双指针--复写零
算法·leetcode·职场和发展
小满zs4 小时前
Go语言第八章(函数)
后端·go
To_OC5 小时前
LC 438 找到所有字母异位词:暴力超时后,我靠滑动窗口一招搞定
javascript·算法·leetcode
白狐_7985 小时前
408数据结构第5章:二叉树遍历序列题——技巧、判断与真题型总结
数据结构
stark张宇6 小时前
实战Go高级特性:Context超时控制、defer资源回收与Channel通信的关键避坑点
后端·go
Forever Nore8 小时前
学完C语言力扣第一题做不来正常吗
数据结构·算法
hansang_IR8 小时前
【题解】LC:倍增 / 区间并查集(Range Parallel Unionfind)
c++·算法·并查集
Tisfy10 小时前
LeetCode 3731.找出缺失的元素:哈希 / 排序
算法·leetcode·哈希算法·排序·哈希表
lucas_AI10 小时前
Q-CueGraph:你的多模态大模型会 zoom,但真的知道该看哪儿吗?
人工智能·算法