1658. Minimum Operations to Reduce X to Zero
Question
You are given an integer array
nums
and an integerx
. In one operation, you can either remove the leftmost or the rightmost element from the arraynums
and subtract its value fromx
. Note that this modifies the array for future operations.Return *the minimum number of operations to reduce
x
to exactly0
if it is possible, otherwise, return *-1
.
Solution
将原有问题的从两边减去一定的值,寻找加和为x的问题转换为寻找滑动窗口中的总和为total - x的新问题。
滑动窗口
初始化当前窗口内的sum,左侧指针left与右侧指针right。
每次将一个新的元素nums[right]加入窗口范围。
当当前的sum大于寻找的target,则将nums[left]滑出窗口,更新left与sum的值。
如果当前窗口内的sum等于寻找的target,则更新记录最小操作次数的min。
Code
1 | class Solution { |
1658. Minimum Operations to Reduce X to Zero
https://xuanhe95.github.io/2022/06/11/1658-Minimum-Operations-to-Reduce-X-to-Zero/