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

}

相关推荐
蒙奇D索大8 分钟前
【数据结构】图论最短路径算法深度解析:从BFS基础到全算法综述
数据结构·算法·图论·广度优先·图搜索算法
trouvaille9 分钟前
哈希数据结构的增强
算法·go
我不是小upper24 分钟前
L1和L2核心区别 !!--part 2
人工智能·深度学习·算法·机器学习
liujing102329292 小时前
Day09_刷题niuke20250609
java·c++·算法
不7夜宵2 小时前
力扣热题100 k个一组反转链表题解
算法·leetcode·链表
蒟蒻小袁3 小时前
力扣面试150题--课程表
算法·leetcode·面试
闻缺陷则喜何志丹3 小时前
【动态规划】B4336 [中山市赛 2023] 永别|普及+
c++·算法·动态规划·洛谷
不二狗4 小时前
每日算法 -【Swift 算法】电话号码字母组合
开发语言·算法·swift
AL流云。4 小时前
【优选算法】分治
数据结构·算法·leetcode·排序算法
行驶5 小时前
数据结构 - 栈与队列
数据结构