算法训练Day32|● 122.买卖股票的最佳时机II ● 55. 跳跃游戏 ● 45.跳跃游戏II

LeetCode:122.买卖股票的最佳时机II

122. 买卖股票的最佳时机 II - 力扣(LeetCode)

思路

当天买卖利润为0,所以索引直接从1开始即可,隔天利润与0取最大值,一直循环加和输出即可

代码实现
1class Solution {
2    public int maxProfit(int[] prices) {
3        int res = 0;
4        for (int i = 1; i < prices.length; i++) {
5            res += Math.max(prices[i] - prices[i - 1], 0);
6        }
7        return res;
8    }
9}
复杂度分析

时间复杂度:O(n).
空间复杂度:O(1).

LeetCode:55. 跳跃游戏

55. 跳跃游戏 - 力扣(LeetCode)

思路

顺序遍历,只能局限于当前索引下元素值范围内,并保存最大值,只要i+nums[i] >= nums.length - 1 ,即可返回
特殊情况:只有一个元素直接返回true.

代码实现
 1// 顺序遍历
 2class Solution {
 3    public boolean canJump(int[] nums) {
 4        if (nums.length == 1) {
 5            return true;
 6        }
 7        int cover = 0;
 8        for (int i = 0; i <= cover; i++) {
 9            cover = Math.max(i + nums[i], cover);
10            if (cover >= nums.length - 1) {
11                return true;
12            }
13        }
14        return false;
15    }
16}
17
18// 逆序遍历:看懂了顺序遍历,逆序似乎更好理解
19class Solution {
20    public boolean canJump(int[] nums) {
21        int lastPos = nums.length - 1;
22        for (int i = nums.length - 2; i >= 0; i--) {
23            if (i + nums[i] >= lastPos) {
24                lastPos = i;
25            }
26        }
27        return lastPos == 0;
28    }
29}
复杂度分析

时间复杂度:最大为O(n).
空间复杂度:O(1)

LeetCode:45.跳跃游戏II

45. 跳跃游戏 II - 力扣(LeetCode)

思路

需要清晰需要几个变量,计数器,当前索引下的最大覆盖范围.

代码实现
 1class Solution {
 2    public int jump(int[] nums) {
 3        if (nums.length == 1) {
 4            return 0;
 5        }
 6        // 计数器
 7        int count = 0;
 8        // 当前索引下的最大覆盖范围
 9        int curDistance = 0;
10        // 该覆盖范围下的覆盖范围
11        int maxDistance = 0;
12
13        for (int i = 0; i < nums.length; i++) {
14            maxDistance = Math.max(maxDistance, i + nums[i]);
15
16            if (maxDistance >= nums.length - 1) {
17                count++;
18                break;
19            } else if (i == curDistance) {
20                curDistance = maxDistance;
21                count++;
22            }
23        }
24        return count;
25    }
26}
复杂度分析

时间复杂度:O(n).
空间复杂度:O(1).

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值