Maximum Beauty of an Array After Applying Operation

Medium Topics Company Tags

For each index of nums, you may replace its value once with any integer in the inclusive range from nums[i] - k to nums[i] + k. You may also leave it unchanged.

The beauty of an array is the greatest number of equal values in a subsequence; those values do not need to be adjacent. Return the maximum beauty obtainable after any allowed replacements.

Example 1:

Input: nums = [1,3,5]
k = 1

Output: 2

Explanation: The values 1 and 3 can both become 2, or 3 and 5 can both become 4. The allowed ranges of 1 and 5 do not overlap, so making all three equal is impossible.

Example 2:

Input: nums = [2,2,4]
k = 0

Output: 2

Explanation: With k = 0, no value can change. The value 2 already occurs twice, which is the maximum beauty.

Example 3:

Input: nums = [0,10]
k = 5

Output: 2

Explanation: Change 0 to 5 and 10 to 5. Both changes are within distance 5, giving two equal values.

Constraints:

  • 1 <= nums.length <= 100000
  • 0 <= nums[i] <= 100000
  • 0 <= k <= 100000


Topics

Company Tags

Please upgrade to NeetCode Pro to view company tags.