Maximum Beauty of an Array After Applying Operation - Sliding Window & Sorting [JS]
Solution: Sliding Window & Sorting
Sort nums in asc order.
Maintain a sliding window with maximum difference of k * 2
.
Record the longest length of the sliding window.
Time Complexity: O(n log(n))
Space Complexity: O(log(n))
(space for sorting)
var maximumBeauty = function(nums, k) {
nums.sort((a, b) => a - b);
let ans = 0, n = nums.length;
for (let j = 0, i = 0; j < n; j++) {
while (nums[j] - nums[i] > k * 2) i++;
ans = Math.max(ans, j - i + 1);
}
return ans;
};
Comments
Post a Comment