Re: [闲聊] 每日leetcode

楼主: dont   2024-11-19 20:26:11
2461. Maximum Sum of Distinct Subarrays With Length K
## 思路
Sliding window
用HashSet记录window内出现过的数字
如果有重复或是window太长就移动left
## CODE
```python
class Solution:
def maximumSubarraySum(self, nums: List[int], k: int) -> int:
n = len(nums)
seen = set()
res = left = curr = 0
for right in range(n):
while nums[right] in seen or right - left + 1 > k:
seen.remove(nums[left])
curr -= nums[left]
left += 1
curr += nums[right]
seen.add(nums[right])
if right - left + 1 == k:
res = max(res, curr)
return res
```

Links booklink

Contact Us: admin [ a t ] ucptt.com