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 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: 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
Maximum Beauty: Transform [4,6,1,2] with k=24612[2,6][4,8][-1,3][0,4]Target Value RangeTarget = 3333Maximum Beauty = 3
Understanding the Visualization
1
Input Array
[4,6,1,2] with k=2, each element can change by ±2
2
Transform Ranges
Each element gets a range: 4→[2,6], 6→[4,8], 1→[-1,3], 2→[0,4]
3
Find Overlaps
Target value 3 can be reached by elements 4,1,2 (beauty=3)
Key Takeaway
🎯 Key Insight: Sort the array first, then use sliding window to find the maximum number of elements whose transformation ranges can overlap
Asked in
Google 12 Amazon 8 Microsoft 6
12.5K Views
Medium Frequency
~25 min Avg. Time
324 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen