Ctrl K

Best Sum of Long Segments

Medium
You get an array values and integers count and min_len. Pick exactly count non-overlapping segments (contiguous subarrays), each at least min_len long, so that the total of all elements inside the chosen segments is as large as possible. Return that largest total. Elements between segments may be left out.
Example 1
values=[4, -1, 2, -9, 3, 3], count=2, min_len=2 → 11

Take [4, -1, 2] with sum 5 and [3, 3] with sum 6, for 11 in total.

Example 2
values=[-5, -2, -7], count=3, min_len=1 → -14

Three segments out of three elements means each element on its own: −5 − 2 − 7 = −14.

Example 3
values=[1, 2, 3, 4], count=1, min_len=3 → 10
Constraints
  • 1 ≤ len(values) ≤ 2000
  • -10⁴ ≤ values[i] ≤ 10⁴
  • 1 ≤ min_len ≤ 3
  • 1 ≤ count ≤ ⌊len(values) / min_len⌋
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsSplit for the Best Averages MediumThe Growing Grab Limit MediumSegments With an Odd Sum MediumCalm Before and After MediumValley Floor Points Medium
loading Python…
Input
values=[4, -1, 2, -9, 3, 3], count=2, min_len=2
Expected
11

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