Minimum Operations to Reduce X to Zero

medium sliding window prefix sum

Problem

You have an array of positive integers nums and an integer x. In one operation you may remove either the leftmost or the rightmost element of the array and subtract its value from x. Find the smallest number of operations that brings x exactly to 0, or return −1 if no combination of edge removals can do it.

Inputnums = [1,1,4,2,3], x = 5
Output2
Removing the last two elements (3, then 2) subtracts exactly 5 from x, so 2 operations suffice.

def min_operations(nums, x):
    target = sum(nums) - x
    if target < 0:
        return -1
    if target == 0:
        return len(nums)
    best = -1
    cur = 0
    left = 0
    for right in range(len(nums)):
        cur += nums[right]
        while cur > target:
            cur -= nums[left]
            left += 1
        if cur == target:
            best = max(best, right - left + 1)
    return -1 if best < 0 else len(nums) - best
function minOperations(nums, x) {
  const target = nums.reduce((a, b) => a + b, 0) - x;
  if (target < 0) return -1;
  if (target === 0) return nums.length;
  let best = -1, cur = 0, left = 0;
  for (let right = 0; right < nums.length; right++) {
    cur += nums[right];
    while (cur > target) {
      cur -= nums[left];
      left++;
    }
    if (cur === target) {
      best = Math.max(best, right - left + 1);
    }
  }
  return best < 0 ? -1 : nums.length - best;
}
int minOperations(int[] nums, int x) {
    int target = -x;
    for (int v : nums) target += v;
    if (target < 0) return -1;
    if (target == 0) return nums.length;
    int best = -1, cur = 0, left = 0;
    for (int right = 0; right < nums.length; right++) {
        cur += nums[right];
        while (cur > target) {
            cur -= nums[left];
            left++;
        }
        if (cur == target) {
            best = Math.max(best, right - left + 1);
        }
    }
    return best < 0 ? -1 : nums.length - best;
}
int minOperations(vector<int>& nums, int x) {
    long target = accumulate(nums.begin(), nums.end(), 0L) - x;
    if (target < 0) return -1;
    if (target == 0) return nums.size();
    int best = -1, left = 0;
    long cur = 0;
    for (int right = 0; right < (int)nums.size(); right++) {
        cur += nums[right];
        while (cur > target) {
            cur -= nums[left];
            left++;
        }
        if (cur == target) {
            best = max(best, right - left + 1);
        }
    }
    return best < 0 ? -1 : (int)nums.size() - best;
}
Time: O(n) Space: O(1)