Problem 369235 · medium · Level 03 Linear Management & Searching

Trim the Ends to a Total

sliding window · variable-size window · complement

A log nums of positive integers can be trimmed by repeatedly deleting either its first or its last element. You must delete elements whose values add up to exactly x. Return the minimum number of deletions needed, or -1 if it is impossible.

Examples

Input:  nums = [1, 1, 4, 2, 3], x = 5
Output: 2
Explanation: delete the last two elements (2 + 3).

Input:  nums = [5, 6, 7, 8, 9], x = 4
Output: -1

Input:  nums = [3, 2, 20, 1, 1, 3], x = 10
Output: 5

Constraints

  • 1 <= len(nums) <= 10**5
  • 1 <= nums[i] <= 10**4, 1 <= x <= 10**9
  • Target complexity: O(n) time; trying every prefix/suffix combination (O(n²)) is too slow for the largest tests.

Goals

  • Reframe removing from both ends as keeping a contiguous middle
  • Find the longest window with an exact sum using positive values
Starting Python…