KatInterview

Find the Highest-Scoring Boundary Pair in an Array

Greedy & IntervalsAuto-graded · 22 test cases
MediumAuto-gradedGreedy & Intervalsarraysgreedytwo-pointers

Last 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 left to index right, inclusive.
  • Subtract the sum of every element that lies strictly between left and right (i.e., indices left+1 through right-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 equals nums[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 equals nums[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.