Maximum sum of smallest and second smallest in an array - GeeksforGeeks

01 Sep, 2021
Input : arr[] = [4, 3, 1, 5, 6]
Output : 11
Subarrays with smallest and second smallest are,
[4, 3]        smallest = 3    second smallest = 4
[4, 3, 1]    smallest = 1    second smallest = 3
[4, 3, 1, 5]    smallest = 1    second smallest = 3
[4, 3, 1, 5, 6]    smallest = 1    second smallest = 3
[3, 1]         smallest = 1    second smallest = 3
[3, 1, 5]     smallest = 1    second smallest = 3
[3, 1, 5, 6]    smallest = 1    second smallest = 3
[1, 5]        smallest = 1    second smallest = 5
[1, 5, 6]    smallest = 1    second smallest = 5
[5, 6]         smallest = 5    second smallest = 6
Maximum sum among all above choices is, 5 + 6 = 11

Input : arr[] =  {5, 4, 3, 1, 6}
Output : 9
 
A simple solution is to generate all subarrays, find sum of smallest and second smallest of every subarray. Finally return maximum of all sums.An efficient solution is based on the observation that this problem reduces to finding a maximum sum of two consecutive elements in array. 
If (x,y) is the pair ,such that (x+y) is the answer , then x and y must be consecutive elements in the array.
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 thatthey 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,
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
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. 
CPP
JAVA
Python3
C#
PHP
Javascript
// C++ program to get max sum with smallest// and second smallest element from any subarray#include <bits/stdc++.h>using namespace std; /*  Method returns maximum obtainable sum value    of smallest and the second smallest value    taken over all possible subarrays */int pairWithMaxSum(int arr[], int N){   if (N < 2)     return -1;    // Find two consecutive elements with maximum   // sum.   int res = arr[0] + arr[1];   for (int i=1; i<N-1; i++)      res = max(res, arr[i] + arr[i+1]);    return res;} //  Driver code to test above methodsint main(){    int arr[] = {4, 3, 1, 5, 6};    int N = sizeof(arr) / sizeof(int);     cout << pairWithMaxSum(arr, N) << endl;    return 0;}
// Java program to get max sum with smallest// and second smallest element from any subarrayimport java.lang.*;class num{ // Method returns maximum obtainable sum value// of smallest and the second smallest value// taken over all possible subarrays */static int pairWithMaxSum(int[] arr, int N){if (N < 2)    return -1; // Find two consecutive elements with maximum// sum.int res = arr[0] + arr[1];for (int i=1; i<N-1; i++)    res = Math.max(res, arr[i] + arr[i+1]); return res;} // Driver programpublic static void main(String[] args){    int arr[] = {4, 3, 1, 5, 6};    int N = arr.length;    System.out.println(pairWithMaxSum(arr, N));}}//This code is contributed by//Smitha Dinesh Semwal
# Python 3 program to get max# sum with smallest and second# smallest element from any# subarray # Method returns maximum obtainable# sum value of smallest and the# second smallest value taken# over all possible subarraysdef pairWithMaxSum(arr, N):     if (N < 2):        return -1         # Find two consecutive elements with    # maximum sum.    res = arr[0] + arr[1]         for i in range(1, N-1):        res = max(res, arr[i] + arr[i + 1])         return res     # Driver codearr = [4, 3, 1, 5, 6]N = len(arr) print(pairWithMaxSum(arr, N)) # This code is contributed by Smitha Dinesh Semwal
// C# program to get max sum with smallest// and second smallest element from any subarrayusing System; class GFG { // Method returns maximum obtainable sum value// of smallest and the second smallest value// taken over all possible subarraysstatic int pairWithMaxSum(int []arr, int N){     if (N < 2)    return -1; // Find two consecutive elements// with maximum sum.int res = arr[0] + arr[1];for (int i = 1; i < N - 1; i++)    res = Math.Max(res, arr[i] + arr[i + 1]); return res;} // Driver codepublic static void Main(){    int []arr = {4, 3, 1, 5, 6};    int N = arr.Length;    Console.Write(pairWithMaxSum(arr, N));}} // This code is contributed by Nitin Mittal.
<?php// PHP program to get max sum with smallest// and second smallest element from any subarray /* Method returns maximum   obtainable sum value   of smallest and the   second smallest value   taken over all possible   subarrays */function pairWithMaxSum( $arr, $N){    if ($N < 2)        return -1;         // Find two consecutive    // elements with maximum    // sum.    $res = $arr[0] + $arr[1];    for($i = 1; $i < $N - 1; $i++)        $res = max($res, $arr[$i] +                    $arr[$i + 1]);         return $res;}     // Driver Code    $arr = array(4, 3, 1, 5, 6);    $N = count($arr);     echo pairWithMaxSum($arr, $N); // This code is contributed by anuj_67.?>
// javascript program to get max sum with smallest// and second smallest element from any subarray   // Method returns maximum obtainable sum value// of smallest and the second smallest value// taken over all possible subarrays function pairWithMaxSum(arr,  N){       if (N < 2)    return -1;   // Find two consecutive elements// with maximum sum. var res = arr[0] + arr[1];for (var i = 1; i < N - 1; i++)    res = Math.max(res, arr[i] + arr[i + 1]);   return res;}   // Driver code     var arr = [4, 3, 1, 5, 6]    var N = arr.length;    document.write(pairWithMaxSum(arr, N)); // This code is contributed by bunnyram19.
Output:  
11
Time Complexity : O(n)Thanks to Md Mishfaq Ahmed for suggesting this approach.This article is contributed by Utkarsh Trivedi. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. 
nitin mittal
vt_m
bunnyram19
sourashis69
Arrays
Stack
Arrays
Stack
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Maximum and minimum of an array using minimum number of comparisons
Stack Data Structure (Introduction and Program)
Top 50 Array Coding Problems for Interviews
Multidimensional Arrays in Java
Introduction to Arrays
Stack Data Structure (Introduction and Program)
Stack Class in Java
Stack in Python
Check for Balanced Brackets in an expression (well-formedness) using Stack
Program for Tower of Hanoi