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

}

相关推荐
纪元A梦18 小时前
贪心算法应用:配送路径优化问题详解
算法·贪心算法
C_player_00118 小时前
——贪心算法——
c++·算法·贪心算法
kyle~20 小时前
排序---插入排序(Insertion Sort)
c语言·数据结构·c++·算法·排序算法
Boop_wu20 小时前
[数据结构] 队列 (Queue)
java·jvm·算法
hn小菜鸡20 小时前
LeetCode 3643.垂直翻转子矩阵
算法·leetcode·矩阵
2301_7703737320 小时前
数据结构之跳表
数据结构
散11220 小时前
01数据结构-初探动态规划
数据结构·动态规划
ゞ 正在缓冲99%…21 小时前
leetcode101.对称二叉树
算法
YuTaoShao1 天前
【LeetCode 每日一题】3000. 对角线最长的矩形的面积
算法·leetcode·职场和发展
2zcode1 天前
基于Matlab可见光通信系统中OOK调制的误码率性能建模与分析
算法·matlab·php