[LeetCode] 2779. Maximum Beauty of an Array After Applying Operation

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).

Constraints:
1 <= nums.length <= 105
0 <= nums[i], k <= 105

数组的最大美丽值。

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

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

在范围 [0, nums.length - 1] 中选择一个 此前没有选过 的下标 i 。
将 nums[i] 替换为范围 [nums[i] - k, nums[i] + k] 内的任一整数。
数组的 美丽值 定义为数组中由相等元素组成的最长子序列的长度。

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

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

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

思路

这道题有多种思路,这里我提供一个滑动窗口的思路。我参考了这个帖子

题目允许我们把数组中的每一个数字 nums[i] 替换成 [nums[i] - k, nums[i] + k] 范围内的任意整数,且让我们找的是一个最长的子序列。因为找的是子序列,而且数字是可以改的,所以这里我们可以对 input 数组排序

排序过后,假如我们最终找到的最长子序列是 [left, left + 1, left + 2,..., right],那么这段子序列需要满足最小值 left + k >= 最大值 right - k。把这个式子变一下,就是right - left <= 2k。这样一来,当我们把 input 数组排过序之后,我们就可以用滑动窗口了。

复杂度

时间O(nlogn)
空间O(1)

代码

Java实现

class Solution {
    public int maximumBeauty(int[] nums, int k) {
        int n = nums.length;
        Arrays.sort(nums);
        int res = 0;
        int start = 0;
        int end = 0;
        while (end < n) {
            while (nums[end] - nums[start] > k * 2) {
                start++;
            }
            res = Math.max(res, end - start + 1);
            end++;
        }
        return res;
    }
}
// sliding window
posted @ 2024-12-19 03:04  CNoodle  阅读(7)  评论(0编辑  收藏  举报