KatInterview

Best Subarray Sum in a Tiled Sequence

Arrays & HashingAuto-graded · 27 test cases
MediumAuto-gradedArrays & Hashingkadanesubarraygreedy

Last updated

Tests whether a candidate can extend Kadane's algorithm to a sequence formed by repeating an array k times, handling boundary crossings and all-negative inputs.

You are given an integer array tiles and a positive integer k. Construct a tiled sequence by concatenating tiles with itself exactly k times. Return the largest possible sum of a non-empty contiguous segment of the tiled sequence.

Rules

  • A segment is a contiguous, non-empty run of elements. It may start in one copy of tiles and end in a later copy, or span several complete copies in the middle.
  • Because the segment must be non-empty, the answer can be negative — this happens when every element of tiles is negative.
  • Return the exact integer sum; do not apply any modulo.

Approach guidance

A good way to build toward the full solution is to start with k = 1 (the best segment within a single copy), then figure out how to extend your reasoning to arbitrary k without constructing the full tiled sequence.

Constraints

  • 1 <= len(tiles) <= 10^5
  • -10^4 <= tiles[i] <= 10^4
  • 1 <= k <= 10^5
  • The tiled sequence can contain up to 10^10 elements — do not build it in memory.
  • The answer's absolute value fits within 2^53, so Python's native integers are sufficient; in other languages use a 64-bit integer type.

Examples

Example 1

Input: best_tiled_subarray_sum([2, -5, 3], 3)

Output: 5

Example 2

Input: best_tiled_subarray_sum([1, -3, 4], 3)

Output: 8

Example 3

Input: best_tiled_subarray_sum([-4, -2, -7], 5)

Output: -2

Hints

Hint 1

Start with the single-copy case (k = 1). A classic linear-scan algorithm can find the best non-empty subarray sum — make sure it handles all-negative arrays correctly by seeding from the first element rather than from zero.

Hint 2

For k >= 2, any segment that crosses at least one copy boundary can be decomposed into: a non-empty suffix of one copy, zero or more complete middle copies, and a non-empty prefix of a later copy. Think about what determines how many middle copies to include.

Hint 3

The sign of sum(tiles) is the deciding factor: if sum(tiles) <= 0, adding whole copies never improves the answer, so two copies of tiles contain the optimal segment. If sum(tiles) > 0, use k - 2 complete middle copies and compute the bonus separately — no need to iterate.