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

}

相关推荐
Queenie_Charlie2 分钟前
和为k的连续区间
数据结构·c++·map
CoderYanger13 分钟前
动态规划算法-简单多状态dp问题:16.买卖股票的最佳时机含手续费
开发语言·算法·leetcode·动态规划·1024程序员节
严文文-Chris27 分钟前
【半监督学习常见算法】
学习·算法·机器学习
爱学java的ptt35 分钟前
206反转链表
数据结构·链表
FPGA_无线通信36 分钟前
OFDM 同步设计(3)
算法·fpga开发
SHOJYS42 分钟前
离散化+二位前缀和的计数题 [USACO20DEC] Rectangular Pasture S
算法
java修仙传1 小时前
力扣hot100:最大子数组和
数据结构·算法·leetcode
hweiyu001 小时前
数据结构:二叉树
数据结构
想唱rap1 小时前
C++之unordered_set和unordered_map
c++·算法·哈希算法
Rock_yzh1 小时前
LeetCode算法刷题——54. 螺旋矩阵
数据结构·c++·学习·算法·leetcode·职场和发展·矩阵