Best Subarray Sum in a Tiled Sequence
Arrays & HashingAuto-graded · 27 test casesLast 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
tilesand 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
tilesis 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^41 <= k <= 10^5- The tiled sequence can contain up to
10^10elements — 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.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Step 1 — Single copy with Kadane's algorithm
For k = 1, the answer is just the maximum non-empty subarray sum of tiles. Kadane's algorithm does this in O(n) time with O(1) extra space:
- Keep a running sum
currepresenting the best subarray sum that ends at the current position. - At each element
x, either extend the previous run (cur + x) or discard it and start fresh (x). Choose whichever is larger:cur = x if cur < 0 else cur + x. - Track the global best across all positions.
The critical detail: seed both cur and best from tiles[0], not from 0. Seeding from 0 would return 0 on an all-negative input, which is wrong — the problem requires a non-empty segment, so the answer must be the least-negative element.
Step 2 — General k, case analysis on the total
Any segment of the tiled sequence is one of two shapes:
- Fits inside one copy — a plain subarray of
tiles. - Crosses at least one boundary — a non-empty suffix of some copy, then
mcomplete copies (0 <= m <= k - 2), then a non-empty prefix of the next copy. Its sum issuffix_sum + m * total + prefix_sum, wheretotal = sum(tiles).
The only free parameter that interacts with k is m * total. Its optimal value depends on the sign of total:
Case A — total <= 0: Adding whole copies never increases the sum, so the best choice is m = 0. Every suffix-plus-prefix pair with m = 0 fits inside two consecutive copies, and every single-copy subarray also fits inside two copies. Therefore kadane(tiles + tiles) is both an upper bound and achievable (two copies always exist because k >= 2 in this branch).
Case B — total > 0: More whole copies always help, so push m as high as it can go: m = k - 2. The answer becomes kadane(tiles + tiles) + (k - 2) * total. We still need kadane(tiles + tiles) to capture the best suffix-plus-prefix pair (with no middle copies). A subtle correctness point: when total > 0, the best two-copy result must come from a boundary-crossing segment, not a within-copy segment — if it came from a within-copy segment, the same segment extended across the boundary would score higher, contradicting optimality. So inserting k - 2 full copies between that suffix and prefix gives a valid segment of the k-fold array with the claimed sum.
k = 1 is handled separately because with only one copy a segment cannot wrap from the end back to the start, so scanning tiles + tiles would be wrong.
Why this is correct
- Upper bound: any segment's sum is at most
best2 + (k-2) * max(total, 0)by the shape argument above. - Achievability: the argument in Case B shows the optimum is always realised by a concrete segment of the tiled array.
Complexity
- Time: O(n) — one pass over
2nelements for Kadane, one pass forsum. - Space: O(n) for the concatenated list. An O(1) variant iterates
ioverrange(2*n)and readstiles[i % n], which is a natural follow-up optimisation.
Edge cases to watch
- All negative: Kadane seeded from
tiles[0]returns the largest single element, which is correct. total == 0: falls into Case A; extra copies contribute nothing.k = 2:(k - 2) * totalis0, so the formula reduces tokadane(tiles + tiles)regardless oftotal.- Large values: with
n = 10^5,k = 10^5, andtiles[i] = 10^4the answer can approach10^14, which exceeds 32-bit range but fits in 64-bit or Python's native integers.
Reference solution
from typing import List
def best_tiled_subarray_sum(tiles: List[int], k: int) -> int:
def kadane(arr: List[int]) -> int:
# Seed from arr[0] so the result is never 0 on an all-negative input.
best = cur = arr[0]
for x in arr[1:]:
# Start a new segment if the running sum has gone negative.
cur = x if cur < 0 else cur + x
if cur > best:
best = cur
return best
if k == 1:
return kadane(tiles)
# Two copies capture every within-copy segment and every suffix+prefix pair.
best2 = kadane(tiles + tiles)
total = sum(tiles)
if total > 0:
# The optimal boundary-crossing segment can absorb k-2 full middle copies.
best2 += (k - 2) * total
return best2