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:
- Space:
sort
에서 사용되는 공간 복잡도, V8 Engine의 경우,Timsort
를 사용하기 때문에, 공간 복잡도는 이 된다.- https://v8.dev/blog/array-sort#timsort
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:
- Space: