题目链接:1658. 将 x 减到 0 的最小操作数 - 力扣(LeetCode)
知道滑动窗口,代码却写不出来
objectivec
#define MIN(a ,b) ((a) < (b) ? (a) : (b))
int minOperations(int* nums, int numsSize, int x)
{
int ans = INT_MAX;
int sum = 0;
for (int i = 0; i < numsSize; i++) {
sum += nums[i];
}
if (sum < x) {
return -1;
}
int left = -1;
int right = 0;
int lsum = 0; // left为-1,左边数组为空,前缀和为0
int rsum = sum; // right为0,右边选中整个数组,后缀和为数组和sum
while (left < numsSize) {
if (left != -1) {
lsum += nums[left]; // 更新前缀和
}
while (right < numsSize && lsum + rsum > x) {
rsum -= nums[right++]; // 前缀和后缀和相加大于x,缩小右数组
}
if (lsum + rsum == x) {
ans = MIN(ans, left + 1 + numsSize - right); // 更新最小操作数
}
left++;
}
return ans == INT_MAX ? -1 : ans;
}