⚡Flashcard Drill➔
NeetCode #240LC-1658MediumSliding Window
← Back to All Problems

#240 · #1658 · Minimum Operations to Reduce X to Zero(将 x 减到 0 的最小操作数)

📌 Problem Statement & Constraints

You are given an array nums and an integer x. In one operation you may remove either the leftmost or the rightmost element and subtract it from x. Return the minimum number of operations to reduce x to exactly 0, or -1 if impossible. Constraints: 1 <= nums.length <= 10^5, 1 <= nums[i] <= 10^4, 1 <= x <= 10^9.

💡 Core Algorithmic Approaches

  1. Removing elements from both ends leaves a contiguous subarray in the middle. So the task is to find the longest subarray whose sum equals total - x.
  2. If total - x < 0, no answer exists; if it equals 0, the whole array must be removed.
  3. Use a sliding window for the longest subarray with a given sum. All values are positive, so the window sum is monotone and two pointers work.
  4. The answer is n - (longest subarray length).

💻 Benchmark Python3 Implementation

class Solution:
    def minOperations(self, nums: List[int], x: int) -> int:
        total = sum(nums)
        target = total - x
        if target < 0:
            return -1
        if target == 0:
            return len(nums)          # remove everything
        l = 0
        cur = 0
        best = -1
        for r, v in enumerate(nums):
            cur += v
            while cur > target and l <= r:
                cur -= nums[l]
                l += 1
            if cur == target:
                best = max(best, r - l + 1)
        return len(nums) - best if best != -1 else -1

⚡ Complexity Deep Dive

⏱️ Time Complexity
O(n): one pass with a sliding window.
💾 Space Complexity
O(1): a few scalars.

⚠️ Interview Pitfalls & Follow-ups

  • Searching for the shortest prefix-plus-suffix directly: the complement formulation (longest middle subarray) is far simpler.
  • Forgetting the target == 0 case: it means the entire array must be removed, and the sliding window would find an empty subarray of length 0 -- returning n is correct but should be explicit.
  • Using the window with negative values: the constraints guarantee positivity, which is what makes the two-pointer shrink valid.
  • Returning n - best when no subarray matches: best stays -1 and the answer must be -1.
⚡
Test muscle memory on this topic via 3-Layer Flashcards
Active Recall: Mentally formulate Prompt ➔ Math Derivation ➔ Benchmark Implementation in 3 minutes.
🎯 Drill This Card Now➔

🧩 Related Sliding Window Problems

中文速览与面试要点

将 x 减到 0 的最小操作数

给你一个整数数组 nums 和一个整数 x。每一次操作时,你应当移除数组 nums 最左边 或 最右边 的元素,然后从 x 中减去该元素的值。请注意,需要 修改 数组以供接下来的操作使用。如果可以将 x 恰好 减到 0,返回 最小操作数 ;否则,返回 −1。约束:1 ≤ nums.length ≤ 10^5;1 ≤ nums[i] ≤ 10^4;1 ≤ x ≤ 10^9。

核心要点

  • 转化为「找最长的中间子数组」(关键洞察) :从两端移除若干元素、剩余中间一段,等价于「保留一个连续子数组,其和 = total − x」。操作数 = n − 子数组长度 ,因此要最大化子数组长度。
  • 滑动窗口求最长子数组 :数组元素全为正,因此可以用滑动窗口找「和恰好等于 total − x 的最长子数组」。
  • 边界处理 :若 total &lt; x 则无解返回 −1;若 total == x 则需移除全部,答案为 n。
  • 为什么能用滑动窗口 :元素全为正数,窗口和随右扩而增、随左缩而减,具有单调性。

常见陷阱

  • 忘记 target &lt; 0 的判定 :此时无解,应返回 −1。
  • 忘记 target == 0 的特判 :此时需移除全部元素,答案为 n。若不特判,滑动窗口会因 cur &gt; 0 立即收缩,找不到和为 0 的子数组(空子数组长度为 0),最终返回 −1。
  • 收缩条件写成 while cur &gt;= target :那会把等于 target 的窗口也破坏掉。必须是 cur &gt; target 。
  • 直接模拟「每次移除左端或右端」 :这是 2^n 的搜索空间,不可行。必须转化为「最长中间子数组」。
  • 数组含负数时仍用滑动窗口 :本题约束 nums[i] ≥ 1,因此可用;若含负数需改用前缀和 + 哈希表。

参考实现

class Solution:
    def minOperations(self, nums: list[int], x: int) -> int:
        total = sum(nums)
        target = total - x              # 需要保留的中间子数组之和
        if target < 0:
            return -1
        if target == 0:
            return len(nums)            # 全部移除

        l = 0
        cur = 0
        best_len = -1
        for r, v in enumerate(nums):
            cur += v
            while cur > target:         # 元素全为正,可安全收缩
                cur -= nums[l]
                l += 1
            if cur == target:
                if r - l + 1 > best_len:
                    best_len = r - l + 1

        return -1 if best_len == -1 else len(nums) - best_len