Input : arr[] = [4, 3, 1, 5, 6]
Output : 11
Subarrays with smallest and second smallest are,
Subarray: [4, 3], smallest = 3, second smallest = 4, sum = 7
Subarray: [4, 3, 1], smallest = 1, second smallest = 3, sum = 4
Subarray: [4, 3, 1, 5], smallest = 1, second smallest = 3, sum = 4
Subarray: [4, 3, 1, 5, 6], smallest = 1, second smallest = 3, sum = 4
Subarray: [3, 1], smallest = 1, second smallest = 3, sum = 4
Subarray: [3, 1, 5], smallest = 1, second smallest = 3, sum = 4
Subarray: [3, 1, 5, 6], smallest = 1, second smallest = 3, sum = 4
Subarray: [1, 5], smallest = 1, second smallest = 5, sum = 6
Subarray: [1, 5, 6] ,smallest = 1, second smallest = 5, sum = 6
Subarray: [5, 6], smallest = 5, second smallest = 6, sum = 11
Maximum sum among all above choices is, 5 + 6 = 11
Input : arr[] = {5, 4, 3, 1, 6}
Output : 9
For a subarray with 2 elements, 1st and 2nd smallest elements are those 2 elements. Now, x and y are present in some subarray such that they are the endpoints. Now, x, y must be the smallest 2 elements of that subarray. If there are other elements Z1 , Z2, ……., ZK between x and y, they are greater than or equal to x and y,
Case1 :
- If there is one element z between x and y, then the smaller subarray with the elements max(x,y) and z , should be the answer, because max(x,y) + z >= x + y
Case2:
- If there are more than one elements between x and y, then the subarray within x and y will have all consecutive elements (Zi + Zi+1) >= (x+y), so (x,y) pair can’t be the answer.
- So, by contradictions, x and y must be consecutive elements in the array.