Open In App

Maximum sum of smallest and second smallest in an array

Last Updated : 01 Jul, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Given an array arr[] of positive integers (with length at least 2), find the maximum sum of the smallest and second smallest elements across all subarrays of size ≥ 2.

Examples:

Input: arr[] = [4, 9, 7]
Output: 16
Explanation: All subarrays of size ≥ 2:
[4, 9] → min = 4, second min = 9 → sum = 13
[4, 9, 7] → min = 4, second min = 7 → sum = 11
[9, 7] → min = 7, second min = 9 → sum = 16
Maximum sum is 16, from subarray [9, 7].

Input: arr[] = [5, 4, 3, 1, 6]
Output: 9
Explanation: The subarray [5, 4] gives min = 4, second min = 5 → sum = 9. All other subarrays yield a smaller sum. Hence, the answer is 9.

[Naive Approach] By Exploring all Subarrays - O(n2) Time and O(1) Space

This approach checks all subarrays of size ≥ 2 and tracks the smallest and second smallest elements in each. It updates these two values as it expands the subarray and calculates their sum. The maximum of all such sums is the final answer.

C++
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

int maxSum(vector<int>& arr) {
    int n = arr.size();
    int maxSum = 0;

    // iterate over each element in 
    // the array except the last one
    for (int i = 0; i < n - 1; i++) {
        int mini = arr[i];
        int secondMini = arr[i + 1];

        // iterate over the remaining 
        // elements in the array
        for (int j = i + 1; j < n; j++) {
            if (mini >= arr[j]) {
                secondMini = mini;
                mini = arr[j];
            }
            else if (secondMini > arr[j]) {
                secondMini = arr[j];
            }

            // calculate the current sum of the minimum 
            // and second minimum elements
            int currSum = mini + secondMini;

            // update the maximum sum if 
            // the current sum is greater
            maxSum = max(maxSum, currSum);
        }
    }

    return maxSum;
}

int main() {
    
    vector<int> arr = { 5, 4, 3, 1, 6 };
    int result = maxSum(arr);
    cout << result << endl;
    
}
Java
import java.util.Arrays;

public class GfG {
    public static int maxSum(int[] arr) {
        int n = arr.length;
        int maxSum = 0;

        // iterate over each element in 
        // the array except the last one
        for (int i = 0; i < n - 1; i++) {
            int mini = arr[i];
            int secondMini = arr[i + 1];

            // iterate over the remaining
            // elements in the array
            for (int j = i + 1; j < n; j++) {
                if (mini >= arr[j]) {
                    secondMini = mini;
                    mini = arr[j];
                } else if (secondMini > arr[j]) {
                    secondMini = arr[j];
                }

                // calculate the current sum of the minimum 
                // and second minimum elements
                int currSum = mini + secondMini;

                // update the maximum sum if the
                // current sum is greater
                maxSum = Math.max(maxSum, currSum);
            }
        }

        return maxSum;
    }

    public static void main(String[] args) {
        
        int[] arr = { 5, 4, 3, 1, 6 };
        int result = maxSum(arr);
        System.out.println(result);
        
    }
}
Python
def maxSum(arr):
    n = len(arr)
    maxSum = 0

    # iterate over each element in 
    # the array except the last one
    for i in range(n - 1):
        mini = arr[i]
        secondMini = arr[i + 1]

        # iterate over the remaining 
        # elements in the array
        for j in range(i + 1, n):
            if mini >= arr[j]:
                secondMini = mini
                mini = arr[j]
            elif secondMini > arr[j]:
                secondMini = arr[j]

            # calculate the current sum of the minimum 
            # and second minimum elements
            currSum = mini + secondMini

            # update the maximum sum if
            # the current sum is greater
            maxSum = max(maxSum, currSum)

    return maxSum

if __name__ == "__main__":
    
    arr = [5, 4, 3, 1, 6]
    result = maxSum(arr)
    print(result)
C#
using System;
using System.Linq;

class GfG {
    static int maxSum(int[] arr) {
        int n = arr.Length;
        int maxSum = 0;

        // iterate over each element in 
        // the array except the last one
        for (int i = 0; i < n - 1; i++) {
            int mini = arr[i];
            int secondMini = arr[i + 1];

            // iterate over the remaining
            // elements in the array
            for (int j = i + 1; j < n; j++) {
                if (mini >= arr[j]) {
                    secondMini = mini;
                    mini = arr[j];
                } else if (secondMini > arr[j]) {
                    secondMini = arr[j];
                }

                // calculate the current sum of the minimum 
                // and second minimum elements
                int currSum = mini + secondMini;

                // update the maximum sum if 
                // the current sum is greater
                maxSum = Math.Max(maxSum, currSum);
            }
        }

        return maxSum;
    }

    static void Main() {
        
        int[] arr = { 5, 4, 3, 1, 6 };
        int result = maxSum(arr);
        Console.WriteLine(result);
        
    }
}
JavaScript
function maxSum(arr) {
    let n = arr.length;
    let maxSum = 0;

    // iterate over each element in
    // the array except the last one
    for (let i = 0; i < n - 1; i++) {
        let mini = arr[i];
        let secondMini = arr[i + 1];

        // iterate over the remaining
        // elements in the array
        for (let j = i + 1; j < n; j++) {
            if (mini >= arr[j]) {
                secondMini = mini;
                mini = arr[j];
            } else if (secondMini > arr[j]) {
                secondMini = arr[j];
            }

            // calculate the current sum of the minimum 
            // and second minimum elements
            let currSum = mini + secondMini;

            // update the maximum sum if 
            // the current sum is greater
            maxSum = Math.max(maxSum, currSum);
        }
    }

    return maxSum;
}

// Driver Code
let arr = [5, 4, 3, 1, 6];
let result = maxSum(arr);
console.log(result);

Output
9

[Expected Approach] By maximizing consecutive element sum - O(n) Time and O(1) Space

An efficient solution relies on the key observation that the problem reduces to finding the maximum sum of two consecutive elements in the array.
If (x, y) is the pair that yields the maximum sum of the smallest and second smallest elements across all subarrays, then x and y must be adjacent in the array.

Contradictory Proof:

For any subarray of size 2, the smallest and second smallest elements are simply the two elements themselves.
Now, suppose x and y are two elements in the array that are the endpoints of a subarray and are also the two smallest elements within that subarray.
Let’s consider the elements z1 , z2 , ..., zk that lie between x and y.

Case1 : One element between x and y

If there's only one element z, and it's not smaller than both x and y, then the subarray formed by max(x, y) and z will have a sum that is at least x + y. So, in this case, (x, y) does not give the maximum sum of smallest and second smallest.

Case2: More than one element between x and y

In this case, the subarray between x and y includes multiple pairs like (zi , zi+1 ). Since all intermediate elements are greater than x and y, their sums will be greater than or equal to x + y.

Hence, (x, y) cannot produce the maximum sum.

=> By contradiction, the only possible candidate pairs for the maximum sum of smallest and second smallest in any subarray must be adjacent elements in the array. So it’s sufficient to only check all adjacent pairs.

C++
#include <iostream>
#include <vector>
using namespace std;

int maxSum(vector<int>& arr) {
    int n = arr.size();
    
    // 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;
}

int main() {
    vector<int> arr = {5, 4, 3, 1, 6};

    cout << maxSum(arr) << endl;
    return 0;
}
Java
import java.util.Arrays;

class GfG {
    public static int maxSum(int[] arr) {
        int n = arr.length;

        // 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;
    }

    public static void main(String[] args) {
        
        int[] arr = {5, 4, 3, 1, 6};
        System.out.println(maxSum(arr));
        
    }
}
Python
def maxSum(arr):
    n = len(arr)

    # 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

if __name__ == "__main__":
    arr = [5, 4, 3, 1, 6]
    print(maxSum(arr))
C#
using System;
using System.Linq;

class GfG {
    static int maxSum(int[] arr) {
        int n = arr.Length;

        // 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;
    }

    static void Main() {
        
        int[] arr = {5, 4, 3, 1, 6};
        Console.WriteLine(maxSum(arr));
        
    }
}
JavaScript
function maxSum(arr) {
    const n = arr.length;

    // find two consecutive elements with maximum sum
    let res = arr[0] + arr[1];
    for (let i = 1; i < n - 1; i++)
        res = Math.max(res, arr[i] + arr[i + 1]);

    return res;
}

// Driver Code
const arr = [5, 4, 3, 1, 6];
console.log(maxSum(arr));

Output
9

Next Article
Article Tags :
Practice Tags :

Similar Reads