---
# System prepended metadata

title: 2779. Maximum Beauty of an Array After Applying Operation
tags: [Leetcode, Sliding Window, Medium]

---

Link: https://leetcode.com/problems/maximum-beauty-of-an-array-after-applying-operation/description/
## 思路
由于是要找subsequence 不在乎顺序 因此直接排序然后用sliding window就可以 保证window里面max和min的差小于等于2k
另一种$O(nlogn)$的做法是参考[这里](https://leetcode.com/problems/maximum-beauty-of-an-array-after-applying-operation/solutions/3771308/java-c-python-sliding-window/)
If the window valids max-min<=k*2, we increase the size of window.
If it doesn't valid, we simply slide the window.

The window is increased for valid subarray,
and the window never decreses.

Finally we return the size of window,
which is the length of biggest window valids.
## Code
$O(n^2)$
```python=
class Solution:
    def maximumBeauty(self, nums: List[int], k: int) -> int:
        nums.sort()
        left, ans = 0, 0
        for right in range(len(nums)):
            while left<right and nums[right]-nums[left]>2*k:
                left += 1
            ans = max(ans, right-left+1)
        return ans
```
$O(nlogn)$
```python=
class Solution:
    def maximumBeauty(self, nums: List[int], k: int) -> int:
        nums.sort()
        left, right = 0, 0
        for right in range(len(nums)):
            if nums[right]-nums[left]>2*k:
                left += 1
        return right-left+1
```
