#2779

Maximum Beauty of an Array After Applying Operation

Medium
ArrayBinary SearchSliding WindowSortingSliding WindowSorting
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n log n)
Space
O(1)
O(1)
💡

Intuition

Time O(n log n)Space O(1)

By sorting the array and using a sliding window approach, we can efficiently find the longest subsequence where the difference between the maximum and minimum values is within the allowed range after operations.

⚙️

Algorithm

5 steps
  1. 1Step 1: Sort the array.
  2. 2Step 2: Use two pointers (left and right) to represent the current window of elements.
  3. 3Step 3: Expand the right pointer until the condition nums[right] - nums[left] > 2 * k is violated.
  4. 4Step 4: Calculate the length of the current valid window and update the maximum length.
  5. 5Step 5: Move the left pointer to shrink the window if necessary.
solution.py11 lines
1# Full working Python code
2
3def max_beauty_optimal(nums, k):
4    nums.sort()
5    left = 0
6    max_length = 0
7    for right in range(len(nums)):
8        while nums[right] - nums[left] > 2 * k:
9            left += 1
10        max_length = max(max_length, right - left + 1)
11    return max_length

Complexity note: The sorting step dominates the time complexity, making it O(n log n), while we only use a constant amount of extra space.

  • 1Sorting the array allows us to easily check the range of values that can be made equal.
  • 2Using a sliding window helps efficiently find the longest valid subsequence without unnecessary checks.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.