Maximum Beauty of an Array After Applying Operation - Problem
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
ithat 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: 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.
Input & Output
Example 1 — Basic Case
$
Input:
nums = [4,6,1,2], k = 2
›
Output:
3
💡 Note:
We can transform the array to [4,4,3,4]. Elements at indices 0, 2, and 3 become equal (ignoring order), so beauty = 3.
Example 2 — Large k Value
$
Input:
nums = [1,1,1,1], k = 10
›
Output:
4
💡 Note:
All elements are already equal, so we can make all 4 elements the same value. Beauty = 4.
Example 3 — No Overlap Possible
$
Input:
nums = [1,10], k = 2
›
Output:
1
💡 Note:
Element 1 can become [1-2,1+2] = [-1,3]. Element 10 can become [10-2,10+2] = [8,12]. No overlap possible, so beauty = 1.
Constraints
- 1 ≤ nums.length ≤ 105
- 0 ≤ nums[i], k ≤ 105
Visualization
Tap to expand
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code