Ctrl K

Signed Segment Split

Medium
You get an integer array values. Cut it into one or more contiguous pieces so that every element belongs to exactly one piece. The cost of a piece uses alternating signs: its first element counts with a plus, the second with a minus, the third with a plus again, and so on. For example, the piece [a, b, c, d] costs a - b + c - d. Return the largest possible total cost of all pieces.
Example 1
values=[2, -3, -1, 5] → 9

Split into [2, -3, -1] and [5]: 2 - (-3) + (-1) = 4, plus 5, total 9.

Example 2
values=[-4, -2, -6] → 0

Pieces [-4] and [-2, -6]: -4 + (-2 - (-6)) = -4 + 4 = 0.

Example 3
values=[7] → 7
Constraints
  • 1 ≤ len(values) ≤ 10⁵
  • -10⁹ ≤ values[i] ≤ 10⁹
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsFewest Jumps to the End MediumMost Profitable Streak MediumReach the Last Cell MediumWarehouse Cart Routes MediumCheapest Corner-to-Corner Route Medium
loading Python…
Input
values=[2, -3, -1, 5]
Expected
9

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