Maximize min+max of contiguous subarray
Company: TikTok
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Technical Screen
Quick Answer: This question evaluates understanding of array algorithms and competency in identifying and reasoning about minimum and maximum values within contiguous subarrays, emphasizing extremal value handling.
Constraints
- 2 <= len(nums) <= 200000
- 1 <= nums[i] <= 1000000000
Examples
Input: ([5, 12, 9, 6, 4],)
Expected Output: 21
Explanation: The subarray [12, 9] has min 9 and max 12, giving 21, which is the maximum possible value.
Input: ([3, 8],)
Expected Output: 11
Explanation: There is only one valid subarray, [3, 8], so the answer is 3 + 8 = 11.
Input: ([1, 2, 3, 4, 5],)
Expected Output: 9
Explanation: The best subarray is [4, 5], giving min 4 plus max 5 = 9.
Input: ([10, 1, 10],)
Expected Output: 11
Explanation: The full subarray [10, 1, 10] gives 11, but adjacent subarrays [10, 1] and [1, 10] also give 11.
Input: ([7, 7, 7, 7],)
Expected Output: 14
Explanation: Every valid subarray has min 7 and max 7, so the maximum sum is 14.
Input: ([1000000000, 1, 999999999],)
Expected Output: 1000000001
Explanation: The best adjacent sums are 1000000000 + 1 and 1 + 999999999, so the maximum is 1000000001.
Hints
- For any valid subarray, look at where its maximum element is. Since the subarray has at least two elements, that maximum has at least one neighbor inside the subarray.
- Can every longer subarray's min + max be matched or exceeded by some adjacent pair inside it?