Find the Highest-Scoring Boundary Pair in an Array
Greedy & IntervalsAuto-graded · 22 test casesLast updated
Tests whether a candidate can exploit a telescoping sum identity to reduce an interval scoring problem to a fast two-endpoint selection with careful tie-breaking.
Problem
You are given a zero-indexed integer array nums of length n. For any pair of indices (left, right) with 0 <= left <= right < n, define the boundary score as follows:
- Compute the sum of every element from index
leftto indexright, inclusive. - Subtract the sum of every element that lies strictly between
leftandright(i.e., indicesleft+1throughright-1). - The result is the boundary score of the range
[left, right].
Notice that this simplifies to just the values at the two endpoints. Specifically:
- If
left < right, the boundary score equalsnums[left] + nums[right], because every interior term cancels out. - If
left == right, the interval contains a single element and the interior is empty, so the boundary score equalsnums[left]— the element is not doubled.
Your task: find the range [left, right] that achieves the maximum boundary score over all valid index pairs.
If more than one range ties for the maximum score, return the one with the smallest left. If there is still a tie, return the one with the smallest right.
Return the answer as a list [left, right].
Constraints
1 <= n <= 10^5-10^6 <= nums[i] <= 10^6- The returned list must contain exactly two integers in the order
[left, right].
Examples
Example 1
Input: best_boundary_range([1, 5, 2, 8, 3])
Output: [1, 3]
Example 2
Input: best_boundary_range([10, -2, 10])
Output: [0, 2]
Example 3
Input: best_boundary_range([7])
Output: [0, 0]
Example 4
Input: best_boundary_range([3, -1, 4, 4, 2])
Output: [2, 3]
Hints
Hint 1
The full sum minus the interior sum telescopes: write both sums out term by term and watch what cancels. You only need to look at two positions per candidate interval.
Hint 2
A brute-force O(n²) scan over all pairs is too slow. Instead, sweep from left to right, and for each right endpoint ask: what is the best left endpoint I have seen so far?
Hint 3
Tie-breaking is the tricky part. When updating the running maximum for the left endpoint, update only on a strict improvement — this naturally preserves the earliest index among equals. When comparing a new candidate to the current best answer, compare the full (score, left, right) tuple so the lexicographic winner always survives.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Why the score reduces to two elements
Write out both sums explicitly for left < right:
full sum = nums[left] + nums[left+1] + ... + nums[right-1] + nums[right]
interior sum = nums[left+1] + ... + nums[right-1]
Every interior term appears once in each sum. Subtracting cancels them all, leaving nums[left] + nums[right]. This works regardless of the sign of any element, because each interior value is added once and subtracted once.
The left == right case is separate: the interior is empty (sum = 0), so the score is just nums[left]. The element is counted once, not twice.
Why a brute-force scan is too slow
Checking every ordered pair takes O(n²) time. With n up to 10⁵ that is 10¹⁰ operations — too slow.
Linear scan with a running maximum
Fix the right endpoint and ask: which left endpoint maximises nums[left] + nums[right]? Since nums[right] is constant for a given right, we want the largest nums[left] over all left < right. That is exactly a prefix maximum, which we can maintain in a single left-to-right sweep.
At each position right we consider two candidates:
- Singleton
[right, right]with scorenums[right]. - Best pair
[max_index, right]with scoremax_value + nums[right], wheremax_valueis the largest element seen so far andmax_indexis its earliest occurrence.
We compare each candidate to the running best using the full tuple (score, left, right) in lexicographic order, which automatically enforces the tie-breaking rules (smallest left, then smallest right).
Crucially, we update max_value and max_index after evaluating both candidates for the current right. This guarantees that every pair candidate satisfies left < right strictly.
For the running max update itself we use a strict > comparison, not >=. That preserves the earliest index among all positions that share the maximum value.
Correctness on edge cases
- n = 1: the loop never executes; the function returns
[0, 0]directly. - All negative values, e.g.
[-5, -1, -3]: every pair sums two negatives, so the best singleton (the least-negative element) wins. Singletons must be evaluated explicitly. - Duplicate maximums, e.g.
[5, 5, 5]: the best pair score is 10. Candidates[0,1],[0,2], and[1,2]all tie. The strict>update keepsmax_index = 0, so the pair candidate at each step is[0, right], and the lexicographically smallest winner[0, 1]is found first. - Zeros, e.g.
[0, 0]: the singleton[0,0]and pair[0,1]both score 0. Tuple comparison picks[0, 0]because(0, 0) < (0, 1).
Complexity
- Time: O(n) — one pass through the array.
- Space: O(1) — only a fixed number of scalar variables beyond the input.
Reference solution
from typing import List
def best_boundary_range(nums: List[int]) -> List[int]:
n = len(nums)
best_score = nums[0]
best_interval = [0, 0]
# Tracks the largest value seen among indices 0..right-1,
# and the earliest index that achieves it.
max_value = nums[0]
max_index = 0
for right in range(1, n):
# Candidate A: singleton range [right, right]
singleton_score = nums[right]
singleton = [right, right]
if (singleton_score > best_score or
(singleton_score == best_score and
tuple(singleton) < tuple(best_interval))):
best_score = singleton_score
best_interval = singleton
# Candidate B: pair [max_index, right]
# For a fixed right endpoint, pairing with the largest
# preceding value maximises the score; strict > update
# on max_value ensures max_index is the earliest such index.
pair_score = max_value + nums[right]
pair = [max_index, right]
if (pair_score > best_score or
(pair_score == best_score and
tuple(pair) < tuple(best_interval))):
best_score = pair_score
best_interval = pair
# Fold the current element into the running max only after
# evaluating candidates, so left < right is always guaranteed.
if nums[right] > max_value:
max_value = nums[right]
max_index = right
return best_interval