Best Sum of Extremes in a Contiguous Subarray
Arrays & HashingAuto-graded · 23 test casesLast 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^51 ≤ 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.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Core observation
There are O(n²) subarrays to consider, which makes a brute-force scan quadratic. The key insight collapses that to a single linear pass:
The best answer is always achieved by some adjacent pair.
So the algorithm is just:
answer = max(nums[i] + nums[i+1]) for i in 0 .. n-2
Why this is correct
We show two things:
1. Every adjacent pair is a valid candidate.
The subarray [nums[i], nums[i+1]] has exactly two elements, so it qualifies. Its contribution is exactly nums[i] + nums[i+1], meaning the true answer is at least the best adjacent-pair sum.
2. No longer subarray beats every adjacent pair.
Pick any subarray S with length ≥ 2. Let M be the maximum element of S, located at index p. Because S has at least two elements, p has at least one neighbor index q (either p−1 or p+1) that also falls inside S. Since nums[q] belongs to S, we know nums[q] ≥ m (the minimum of S). Therefore:
nums[p] + nums[q]=M + nums[q]≥M + m
The adjacent pair (p, q) matches or exceeds the (min + max) of the entire subarray S.
Combining both directions: the maximum over all subarrays equals the maximum adjacent-pair sum.
Intuition: extending a subarray can only raise the maximum or lower the minimum. The maximum is always "anchored" at one element, and that element's immediate neighbor is already at least as large as the subarray's minimum. Extending the window never improves the sum.
Note that the proof does not rely on all values being positive — it holds for arbitrary integers.
Common mistake
Returning the sum of the two globally largest values fails on inputs like [10, 1, 10]. Any subarray containing both 10s also contains the 1, so its min is 1 and the best achievable is 11, not 20. The adjacent-pair scan handles this correctly.
Edge cases
n = 2: only one pair exists; the answer isnums[0] + nums[1].- All elements equal (e.g.,
[7, 7, 7]): every subarray gives the same value; any adjacent pair returns it. - Global maximum at a boundary (e.g.,
[20, 1, 1, 1]): the only neighbor of index 0 is index 1, giving21. Longer subarrays containing 20 also have min1, so21is still correct.
Complexity
- Time: O(n) — one pass over the n−1 adjacent pairs.
- Space: O(1) extra — the generator expression produces one value at a time with no auxiliary storage.
A brute-force solution that iterates over all subarrays runs in O(n²) with incremental min/max tracking, or O(n³) naively. That is acceptable as a starting point, but the linear reduction is the target insight.
Follow-up
What if the subarray must have length at least k?
The same argument generalizes: any window of length > k is dominated by a length-k window that contains its maximum element. Slide a window of exactly size k across the array, tracking the min and max with monotonic deques. This again runs in O(n) time.
Reference solution
from typing import List
def best_subarray_range_sum(nums: List[int]) -> int:
# Any subarray of length >= 2 is dominated by the adjacent pair that
# includes its maximum element, so checking all consecutive pairs suffices.
return max(nums[i] + nums[i + 1] for i in range(len(nums) - 1))