leetcode 1658 求固定值的滑动窗口的最长跨度
用左端点控制,还是右端点控制,要注意
class Solution:
def minOperations(self, nums: List[int], x: int) -> int:
tar =sum(nums) -x
if tar<0:return -1
n=len(nums)
if tar==0:return n
#找最长的滑动窗口,窗口总和固定
left =r =ans=he=0
while left<n: #这个地方最开始写了r ,
while r<n and he<tar:
he += nums[r]
r+=1
if he==tar and (t:=r-left)>ans:
ans=t
he-= nums[left]
left+=1
return n - ans if ans else -1
网友评论