Ctrl K

Disjoint Segments With a Target Sum

Medium
You are given an integer array values and an integer goal. A segment is a non-empty run of consecutive elements of the array. Pick as many segments as you can so that each one sums to exactly goal and no two of them share an element. Return how many segments you picked. Elements that end up in no segment are simply left out.
Example 1
values=[2, 4, -1, 3, 3, 1, 5], goal=6 → 3

Segments summing to 6 include [2, 4], [4, -1, 3], [3, 3] and [1, 5]. Without overlaps we can take [2, 4], [3, 3] and [1, 5]: three segments.

Example 2
values=[3, 3, 3, 3, 3], goal=9 → 1

Any three neighbouring 3s add up to 9, but with only five elements just one such segment fits without overlapping.

Example 3
values=[0, 5, 0], goal=0 → 2

Each zero on its own is a segment with sum 0.

Constraints
  • 1 ≤ len(values) ≤ 10⁵
  • -10⁴ ≤ values[i] ≤ 10⁴
  • 0 ≤ goal ≤ 10⁶
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsShift a Segment to Match MediumA Shelf With Matching Ends HardStudios for Recording Sessions MediumLongest Run with a Given Sum MediumA Stretch Divisible by k Medium
loading Python…
Input
values=[2, 4, -1, 3, 3, 1, 5], goal=6
Expected
3

Run checks the first 3 tests in your browser. Submit checks all 94 tests on the server, hidden ones included.