Maximum Beauty of an Array After Applying Operation

MediumArrayBinary SearchSliding WindowSorting

Solution

Solution1: Sliding Window

function maximumBeauty(nums: number[], k: number): number {
  const n = nums.length;
  nums.sort((a, b) => a - b);
 
  let answer = 0;
  let start = 0;
  for (let end = 0; end < n; end++) {
    while (2 * k < nums[end] - nums[start]) {
      start += 1;
    }
    answer = Math.max(answer, end - start + 1);
  }
  return answer;
}

Complexity

  • Time: O(nlogn)O(n \cdot logn)
  • Space: O(S)O(S)

Solution2: Line Sweep

export function maximumBeauty(nums: number[], k: number): number {
  const n = nums.length;
  if (n === 1) {
    return 1;
  }
 
  const maxValue = nums.reduce((prev, num) => (prev > num ? prev : num), 0);
  const counts = new Array<number>(maxValue + 1).fill(0);
  for (const num of nums) {
    counts[Math.max(num - k, 0)] += 1;
    if (num + k + 1 <= maxValue) {
      counts[num + k + 1] -= 1;
    }
  }
 
  let answer = 0;
  let beauty = 0;
  for (const count of counts) {
    beauty += count;
    answer = Math.max(answer, beauty);
  }
  return answer;
}

Complexity

  • Time: O(n+maxValue)O(n + maxValue)
  • Space: O(maxValue)O(maxValue)