欢迎光临散文网 会员登陆 & 注册

LeetCode 6929. 数组的最大美丽值

2023-07-16 12:43 作者:您是打尖儿还是住店呢  | 我要投稿

You are given a 0-indexed array nums and a non-negative integer k.

In one operation, you can do the following:

  • Choose an index i that hasn't been chosen before from the range [0, nums.length - 1].

  • Replace nums[i] with any integer from the range [nums[i] - k, nums[i] + k].

The beauty of the array is the length of the longest subsequence consisting of equal elements.

Return the maximum possible beauty of the array nums after applying the operation any number of times.

Note that you can apply the operation to each index only once.

A subsequence of an array is a new array generated from the original array by deleting some elements (possibly none) without changing the order of the remaining elements.

 

Example 1:

Input: nums = [4,6,1,2], k = 2

Output: 3

Explanation: In this example, we apply the following operations: - Choose index 1, replace it with 4 (from range [4,8]), nums = [4,4,1,2]. - Choose index 3, replace it with 4 (from range [0,4]), nums = [4,4,1,4]. After the applied operations, the beauty of the array nums is 3 (subsequence consisting of indices 0, 1, and 3). It can be proven that 3 is the maximum possible length we can achieve.

Example 2:

Input: nums = [1,1,1,1], k = 10

Output: 4

Explanation: In this example we don't have to apply any operations. The beauty of the array nums is 4 (whole array).

-------------------------------------

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


在一步操作中,你可以执行下述指令:


在范围 [0, nums.length - 1] 中选择一个 此前没有选过 的下标 i 。

将 nums[i] 替换为范围 [nums[i] - k, nums[i] + k] 内的任一整数。

数组的 美丽值 定义为数组中由相等元素组成的最长子序列的长度。


对数组 nums 执行上述操作任意次后,返回数组可能取得的 最大 美丽值。


注意:你 只 能对每个下标执行 一次 此操作。


数组的 子序列 定义是:经由原数组删除一些元素(也可能不删除)得到的一个新数组,且在此过程中剩余元素的顺序不发生改变。


 


示例 1:


输入:nums = [4,6,1,2], k = 2

输出:3

解释:在这个示例中,我们执行下述操作:

- 选择下标 1 ,将其替换为 4(从范围 [4,8] 中选出),此时 nums = [4,4,1,2] 。

- 选择下标 3 ,将其替换为 4(从范围 [0,4] 中选出),此时 nums = [4,4,1,4] 。

执行上述操作后,数组的美丽值是 3(子序列由下标 0 、1 、3 对应的元素组成)。

可以证明 3 是我们可以得到的由相等元素组成的最长子序列长度。

示例 2:


输入:nums = [1,1,1,1], k = 10

输出:4

解释:在这个示例中,我们无需执行任何操作。

数组 nums 的美丽值是 4(整个数组)。

 


提示:


1 <= nums.length <= 105

0 <= nums[i], k <= 105

-------------------------

以2k为区间,找区间内元素的最大值,题目信息一转换,就知道怎么做了,没错,我还是一如既往的笨;

执行用时:39 ms, 在所有 Java 提交中击败了100.00%的用户

内存消耗:57 MB, 在所有 Java 提交中击败了100.00%的用户


LeetCode 6929. 数组的最大美丽值的评论 (共 条)

分享到微博请遵守国家法律