Skip to content

Commit fe7fe36

Browse files
committed
2779. Maximum Beauty of an Array After Applying Operation
1 parent ba77e85 commit fe7fe36

File tree

1 file changed

+24
-0
lines changed

1 file changed

+24
-0
lines changed
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
// Solution by Sergey Leschev
2+
// 2779. Maximum Beauty of an Array After Applying Operation
3+
4+
// Time complexity: O(n log n) for sorting the array.
5+
// Space complexity: O(1) as no extra space is required.
6+
7+
function maximumBeauty(nums: number[], k: number): number {
8+
// Sort the array to simplify the process of finding valid subsequences
9+
nums.sort((a, b) => a - b)
10+
11+
let start = 0 // Pointer for the start of the valid window
12+
let maxBeauty = 0 // Variable to store the maximum beauty (length of longest subsequence)
13+
14+
for (let i = 0; i < nums.length; i++) {
15+
// Ensure the window [start...i] is valid by adjusting the start pointer
16+
while (nums[i] - nums[start] > 2 * k) {
17+
start++
18+
}
19+
// Update the maximum beauty with the current window size
20+
maxBeauty = Math.max(maxBeauty, i - start + 1)
21+
}
22+
23+
return maxBeauty
24+
}

0 commit comments

Comments
 (0)