算法训练营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 天前
递归解题指南:LeetCode经典题全解析
数据结构·算法·leetcode·职场和发展·排序算法·深度优先·递归
Kiling_07041 天前
Java集合进阶:Set与Collections详解
算法·哈希算法
智者知已应修善业1 天前
【51单片机89C51及74LS273、74LS244组成】2022-5-28
c++·经验分享·笔记·算法·51单片机
洛水水1 天前
【力扣100题】33.验证二叉搜索树
算法·leetcode·职场和发展
SimpleLearingAI1 天前
聚类算法详解
算法·数据挖掘·聚类
刀法如飞1 天前
Go 字符串查找的 20 种实现方式,用不同思路解决问题
算法·面试·程序员
feasibility.1 天前
反爬十层妖塔:现代爬虫攻防的立体战争
爬虫·python·科技·scrapy·rust·go·硬件
Dlrb12111 天前
C语言-指针数组与数组指针
c语言·数据结构·算法·指针·数组指针·指针数组·二级指针
WL_Aurora1 天前
Python 算法基础篇之集合
python·算法
平行侠1 天前
A15 工业路由器IP前缀高速检索与内存压缩系统
网络·tcp/ip·算法