KatInterview

Best Sum of Extremes in a Contiguous Subarray

Arrays & HashingAuto-graded · 23 test cases
MediumAuto-gradedArrays & Hashingarraysgreedysliding-window

Last updated

Tests whether a candidate can reduce an O(n²) subarray search to a single linear scan by proving that adjacent pairs always dominate longer windows.

Problem

You are given an array of n positive integers nums.

Your goal is to find a contiguous subarray of length at least 2 that maximizes the quantity:

(smallest element in the subarray) + (largest element in the subarray)

Return that maximum achievable value.

When several subarrays produce the same best value, return the value itself — you do not need to identify the subarray.

You may assume n ≥ 2.


Constraints

  • 2 ≤ n ≤ 10^5
  • 1 ≤ nums[i] ≤ 10^9
  • The subarray must be contiguous and include at least two elements.

Examples

Example 1

Input: best_subarray_range_sum([5, 12, 9, 6, 4])

Output: 21

Example 2

Input: best_subarray_range_sum([1, 2])

Output: 3

Example 3

Input: best_subarray_range_sum([10, 3, 8, 7])

Output: 15

Hints

Hint 1

Start by computing (min + max) for every adjacent pair. What is the best value you can get from those alone?

Hint 2

Now take any subarray longer than 2 elements. Its maximum value appears at some position inside it — that position has at least one neighbor also inside the subarray. What does that tell you about how the adjacent-pair sum compares to (min + max) of the longer subarray?

Hint 3

The previous observation means you never need to look beyond adjacent pairs. One linear scan over all consecutive pairs is sufficient — no monotonic stack or sliding-window deque required.