Skip to content

1658. Minimum Operations to Reduce X to Zero 👍

  • Time: $O(n)$
  • Space: $O(n)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
class Solution {
 public:
  int minOperations(vector<int>& nums, int x) {
    const int targetSum = accumulate(nums.begin(), nums.end(), 0) - x;
    if (targetSum == 0)
      return nums.size();
    const int maxLen = maxSubArrayLen(nums, targetSum);
    return maxLen == -1 ? -1 : nums.size() - maxLen;
  }

 private:
  // Same as 325. Maximum Size Subarray Sum Equals k
  int maxSubArrayLen(vector<int>& nums, int k) {
    int res = -1;
    int prefix = 0;
    unordered_map<int, int> prefixToIndex{{0, -1}};

    for (int i = 0; i < nums.size(); ++i) {
      prefix += nums[i];
      const int target = prefix - k;
      if (const auto it = prefixToIndex.find(target);
          it != prefixToIndex.cend())
        res = max(res, i - it->second);
      // No need to check the existence of the prefix since it's unique.
      prefixToIndex[prefix] = i;
    }

    return res;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
class Solution {
  public int minOperations(int[] nums, int x) {
    final int targetSum = Arrays.stream(nums).sum() - x;
    if (targetSum == 0)
      return nums.length;
    final int maxLen = maxSubArrayLen(nums, targetSum);
    return maxLen == -1 ? -1 : nums.length - maxLen;
  }

  // Same as 325. Maximum Size Subarray Sum Equals k
  private int maxSubArrayLen(int[] nums, int k) {
    int res = -1;
    int prefix = 0;
    Map<Integer, Integer> prefixToIndex = new HashMap<>();
    prefixToIndex.put(0, -1);

    for (int i = 0; i < nums.length; ++i) {
      prefix += nums[i];
      final int target = prefix - k;
      if (prefixToIndex.containsKey(target))
        res = Math.max(res, i - prefixToIndex.get(target));
      // No need to check the existence of the prefix since it's unique.
      prefixToIndex.put(prefix, i);
    }

    return res;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Solution:
  def minOperations(self, nums: List[int], x: int) -> int:
    targetSum = sum(nums) - x
    if targetSum == 0:
      return len(nums)
    maxLen = self._maxSubArrayLen(nums, targetSum)
    return -1 if maxLen == -1 else len(nums) - maxLen

  # Same as 325. Maximum Size Subarray Sum Equals k
  def _maxSubArrayLen(self, nums: List[int], k: int) -> int:
    res = -1
    prefix = 0
    prefixToIndex = {0: -1}

    for i, num in enumerate(nums):
      prefix += num
      target = prefix - k
      if target in prefixToIndex:
        res = max(res, i - prefixToIndex[target])
      # No need to check the existence of the prefix since it's unique.
      prefixToIndex[prefix] = i

    return res