Ctrl K

Best Sum in Whole Blocks

Medium
You get an integer array values and an integer block. Pick a contiguous non-empty segment whose length is a multiple of block (that is, block, 2·block, 3·block and so on) and return the largest possible sum of its elements. Elements can be negative, so the answer can be negative too.
Example 1
values=[3, -1, 4, -6, 2], block=2 → 3

Only even-length segments count. [3, -1, 4, -6] sums to 0 and [3, -1] to 2, while [-1, 4] gives 3, the best.

Example 2
values=[-7, -2, -9], block=3 → -18

The length must be a multiple of 3, so the only choice is the whole array: -7 - 2 - 9 = -18.

Example 3
values=[5, 1, -3, 8], block=1 → 11

With block = 1 any segment works; the whole array is best, with sum 11.

Constraints
  • 1 ≤ block ≤ len(values) ≤ 2·10⁵
  • -10⁹ ≤ values[i] ≤ 10⁹
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsLongest Run with a Given Sum MediumA Stretch Divisible by k MediumAs Many Heads as Tails MediumStretches With an Exact Total MediumWindows With an Exact Alarm Count Medium
loading Python…
Input
values=[3, -1, 4, -6, 2], block=2
Expected
3

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