You are given a 0-indexed integer array nums and a non-negative integer k.
In one operation you can:
-
Choose an index
i
in the range
[0, len(nums) - 1]
that has not been chosen before.
-
Replace
nums[i]
with any integer in the range
[nums[i] - k, nums[i] + k]
.
The beauty of the array is the length of the longest subsequence consisting of equal elements. A subsequence is formed from the array by deleting some elements (possibly none) without changing the order of the remaining elements.
Return the maximum possible beauty of nums after applying the operation any number of times. Each index can be chosen only once.
Function Signature
def maximum_beauty(nums: list[int], k: int) -> int:
Rules
-
The range for index
i
is based on its original value. The replacement may be any integer in that range, including values below 0 or above
10^5
.
-
Indices that are never chosen keep their original values.
Constraints
-
1 <= len(nums) <= 10^5
-
0 <= nums[i], k <= 10^5
Examples
Input: nums = [4, 6, 1, 2], k = 2
Output: 3
Replace nums[1] with 4 and nums[3] with 4. The array becomes [4, 4, 1, 4], and indices 0, 1 and 3 form an equal subsequence of length 3. All four cannot match, because the range for 1 (from -1 to 3) and the range for 6 (from 4 to 8) do not overlap.
Input: nums = [1, 1, 1, 1], k = 10
Output: 4
All elements are already equal, so no operation is needed.
Input: nums = [3, 1, 3, 2, 3], k = 0
Output: 3
With k = 0 no value can change, so the beauty is the count of the most frequent value, 3.