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

}

相关推荐
while(1){yan}1 小时前
数据结构之链表
数据结构·链表
Han.miracle3 小时前
数据结构——二叉树的从前序与中序遍历序列构造二叉树
java·数据结构·学习·算法·leetcode
mit6.8245 小时前
前后缀分解
算法
独自破碎E5 小时前
判断链表是否为回文
数据结构·链表
你好,我叫C小白5 小时前
C语言 循环结构(1)
c语言·开发语言·算法·while·do...while
寂静山林8 小时前
UVa 10228 A Star not a Tree?
算法
Neverfadeaway8 小时前
【C语言】深入理解函数指针数组应用(4)
c语言·开发语言·算法·回调函数·转移表·c语言实现计算器
Madison-No79 小时前
【C++】探秘vector的底层实现
java·c++·算法
Swift社区9 小时前
LeetCode 401 - 二进制手表
算法·leetcode·ssh
派大星爱吃猫9 小时前
顺序表算法题(LeetCode)
算法·leetcode·职场和发展