call(back)
Algorithms & Data StructureseasySign in to star problems

Subarray With the Largest Min Plus Max

Given an array of positive integers, consider every contiguous subarray that contains at least two elements. For each, add its smallest element to its largest. Return the largest such sum.

largestMinMaxSum([5, 12, 9, 6, 4])  ->  21   // [12, 9]: min 9 + max 12
largestMinMaxSum([3, 3])            ->  6

The array has between 2 and 200,000 elements. You have thirty minutes; most of them should go on explaining why your answer is right.

Hints

Hint 1

Write down a few subarrays of length three and compare each with the pairs inside it.

Hint 2

In any subarray, look at the largest element and the neighbour next to it inside the subarray. How does that pair's sum compare with the subarray's min plus max?

Topics

Asked at

Similar Problems6