Skip to content

2779. Maximum Beauty of an Array After Applying Operation 👍

Approach 1: Regular Window

  • Time: $O(n)$
  • Space: $O(1)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
class Solution {
 public:
  int maximumBeauty(vector<int>& nums, int k) {
    int ans = 0;

    ranges::sort(nums);

    for (int l = 0, r = 0; r < nums.size(); ++r) {
      while (nums[r] - nums[l] > 2 * k)
        ++l;
      ans = max(ans, r - l + 1);
    }

    return ans;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
class Solution {
  public int maximumBeauty(int[] nums, int k) {
    int ans = 0;

    Arrays.sort(nums);

    for (int l = 0, r = 0; r < nums.length; ++r) {
      while (nums[r] - nums[l] > 2 * k)
        ++l;
      ans = Math.max(ans, r - l + 1);
    }

    return ans;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
class Solution:
  def maximumBeauty(self, nums: list[int], k: int) -> int:
    ans = 0

    nums.sort()

    l = 0
    for r in range(len(nums)):
      while nums[r] - nums[l] > 2 * k:
        l += 1
      ans = max(ans, r - l + 1)

    return ans

Approach 2: Lazy Window

  • Time: $O(n)$
  • Space: $O(1)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
class Solution {
 public:
  int maximumBeauty(vector<int>& nums, int k) {
    // l and r track the maximum window instead of the valid window.
    int l = 0;
    int r = 0;

    ranges::sort(nums);

    for (r = 0; r < nums.size(); ++r)
      if (nums[r] - nums[l] > 2 * k)
        ++l;

    return r - l;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
class Solution {
  public int maximumBeauty(int[] nums, int k) {
    // l and r track the maximum window instead of the valid window.
    int l = 0;
    int r = 0;

    Arrays.sort(nums);

    for (r = 0; r < nums.length; ++r)
      if (nums[r] - nums[l] > 2 * k)
        ++l;

    return r - l;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
class Solution:
  def maximumBeauty(self, nums: list[int], k: int) -> int:
    nums.sort()

    # l and r track the maximum window instead of the valid window.
    l = 0
    for r in range(len(nums)):
      if nums[r] - nums[l] > 2 * k:
        l += 1

    return r - l + 1