【力扣每日一题】力扣1696跳跃游戏VI

文章介绍了如何解决力扣平台上的1696跳跃游戏问题,通过动态规划的方法计算在给定数组和步数k的情况下,到达数组尾部的最大得分。提供了Java和C++两种编程语言的实现代码.
摘要由CSDN通过智能技术生成

题目来源

力扣1696跳跃游戏VI

题目概述

给你一个下标从 0 开始的整数数组 nums 和一个整数 k 。

一开始你在下标 0 处。每一步,你最多可以往前跳 k 步,但你不能跳出数组的边界。也就是说,你可以从下标 i 跳到** [i + 1, min(n - 1, i + k)] **包含 两个端点的任意位置。

你的目标是到达数组最后一个位置**(下标为 n - 1 )**,你的 得分 为经过的所有数字之和。

请你返回你能得到的 最大得分 。

思路分析

可以使用一个数组来记录到达 i 位置时可以取得的最高分数。这个分数就是i - k到i - 1位置的最高分数 + i位置的分数。

代码实现

java实现

public class Solution {
    public int maxResult(int[] nums, int k) {
		// 记录i位置的最高分数
        int[] answer = new int[nums.length];
		// 记录向前最多k位的最大分数下标
        int maxIndex = 0;
        answer[0] = nums[0];
        for (int i = 1;  i < nums.length; i++) {
			// 我们只需要比较 maxIndex 和 新空出来的位置,就能找出新的最大值
            maxIndex = answer[maxIndex] > answer[i - 1] ? maxIndex : i - 1;
            answer[i] = answer[maxIndex] + nums[i];
			// 如果当前的maxIndex被删除,寻找新的maxIndex
            if (maxIndex <= i - k) {
                maxIndex = i - k + 1;
                for (int j = maxIndex + 1; j < i; j++) {
                    maxIndex = answer[maxIndex] > answer[j] ? maxIndex : j;
                }
            }
        }
        return answer[nums.length - 1];
    }
}

c++实现

class Solution {
public:
    int maxResult(vector<int>& nums, int k) {
		// 记录 i 位置的最高分数
        vector<int> answer = vector<int>(nums.size());
		// 记录可以到达 i 位置的最多前 k 个位置的最高分数
        int maxIndex = 0;
        answer[0] = nums[0];
        for (int i = 1;  i < nums.size(); i++) {
			// 比较最大值和新空出来的位置
            maxIndex = answer[maxIndex] > answer[i - 1] ? maxIndex : i - 1;
            answer[i] = answer[maxIndex] + nums[i];
			// 如果最大值被删除,寻找新的最大值
            if (maxIndex <= i - k) {
                maxIndex = i - k + 1;
                for (int j = maxIndex + 1; j < i; j++) {
                    maxIndex = answer[maxIndex] > answer[j] ? maxIndex : j;
                }
            }
        }
        return answer[nums.size() - 1];
    }
};

  • 3
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值