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 of Array INPUT nums = [4, 6, 1, 2], k = 2 4 i=0 6 i=1 1 i=2 2 i=3 Each element's range (+/- k): 4: [2, 6] 6: [4, 8] 1: [-1, 3] 2: [0, 4] Number line showing overlaps: -1 2 4 6 8 ALGORITHM STEPS 1 Sort the Array Sort nums: [1, 2, 4, 6] 2 Sliding Window Find max window where nums[r] - nums[l] <= 2*k 3 Check Condition If diff > 2*k, shrink left 2*k = 4 (threshold) 4 Track Maximum Update max beauty = r-l+1 Window Analysis: 1 2 4 6 4-1=3 <= 4 (OK) Window size = 3 elements All can become value 3 or 4 FINAL RESULT Selected elements can all become the same value: Original: [4, 6, 1, 2] 4 skip 6 --> 4 1 --> 3 2 --> 3 After operation: [4, 4, 3, 4] or any value in overlap Maximum Beauty 3 OK - Verified 3 elements can be equal Key Insight: Two elements can become equal if their ranges [nums[i]-k, nums[i]+k] overlap. After sorting, use sliding window: elements in window can all be equal if max - min <= 2*k. Time: O(n log n) for sort + O(n) for sliding window = O(n log n). Space: O(1) extra. TutorialsPoint - Maximum Beauty of an Array After Applying Operation | Optimal Solution
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