The Wayback Machine - https://web.archive.org/web/20250415194539/https://www.geeksforgeeks.org/maximum-sum-of-smallest-and-second-smallest-in-an-array/
Open In App

Maximum sum of smallest and second smallest in an array

Last Updated : 05 Jul, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Given an array arr[] of size n, the task is to find the maximum sum of the smallest and second smallest elements among all possible subarrays of size greater than equals to two.

Examples:

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

Approaches to find maximum sum of smallest and second smallest in an array:

[Naive Approach] By Generating all Subarrays – O(n2) time and O(1) auxiliary space

The very basic approach is to generate all subarrays of size >= 2 and for each subarray, find the smallest and second smallest elements and calculate their sum. If their sum is greater than the result then update the result with current maximum sum found.

Code Implementation:

C++
#include <bits/stdc++.h>
using namespace std;

// Function to find the maximum sum of the smallest and
// second smallest numbers
long findMaxSum(vector<int>& arr)
{
    int n = arr.size();

    // Variable to store the maximum sum found
    long maxSum = 0;

    // Iterate over each element in the array except the
    // last one
    for (int i = 0; i < n - 1; i++) {

        // Initialize the minimum element as the current
        // element
        int minn = arr[i];

        // Initialize the second minimum element as the next
        // element
        int secondMinn = arr[i + 1];

        // Iterate over the remaining elements in the array
        for (int j = i + 1; j < n; j++) {
            // Update the minimum and second minimum
            // elements
            if (minn >= arr[j]) {
                secondMinn = minn;
                minn = arr[j];
            }
            else if (secondMinn > arr[j]) {
                secondMinn = arr[j];
            }

            // Calculate the current sum of the minimum and
            // second minimum elements
            long currSum = minn + secondMinn;

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

    // Return the maximum sum found
    return maxSum;
}

// Driver code
int main()
{
    vector<int> arr = { 4, 3, 1, 5, 6 };
    long result = findMaxSum(arr);

    // Output the result
    cout << result;
}
Java
import java.util.*;

public class CircularPrimeChecker {

    // Function to find the maximum sum of the smallest and
    // second smallest numbers
    public static long findMaxSum(List<Integer> arr)
    {
        int n = arr.size();

        // Variable to store the maximum sum found
        long maxSum = 0;

        // Iterate over each element in the array except the
        // last one
        for (int i = 0; i < n - 1; i++) {

            // Initialize the minimum element as the current
            // element
            int minn = arr.get(i);

            // Initialize the second minimum element as the
            // next element
            int secondMinn = arr.get(i + 1);

            // Iterate over the remaining elements in the
            // array
            for (int j = i + 1; j < n; j++) {

                // Update the minimum and second minimum
                // elements
                if (minn >= arr.get(j)) {
                    secondMinn = minn;
                    minn = arr.get(j);
                }
                else if (secondMinn > arr.get(j)) {
                    secondMinn = arr.get(j);
                }

                // Calculate the current sum of the minimum
                // and second minimum elements
                long currSum = minn + secondMinn;

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

        // Return the maximum sum found
        return maxSum;
    }

    // Driver code
    public static void main(String[] args)
    {
        List<Integer> arr = Arrays.asList(4, 3, 1, 5, 6);
        long result = findMaxSum(arr);

        // Output the result
        System.out.println(result);
    }
}
Python
def find_max_sum(arr):

    # Function to find the maximum sum of the smallest and second smallest numbers
    n = len(arr)

    # Variable to store the maximum sum found
    max_sum = 0

    # Iterate over each element in the array except the last one
    for i in range(n - 1):

        # Initialize the minimum element as the current element
        minn = arr[i]

        # Initialize the second minimum element as the next element
        second_minn = arr[i + 1]

        # Iterate over the remaining elements in the array
        for j in range(i + 1, n):

            # Update the minimum and second minimum elements
            if minn >= arr[j]:
                second_minn = minn
                minn = arr[j]
            elif second_minn > arr[j]:
                second_minn = arr[j]

            # Calculate the current sum of the minimum and second minimum elements
            curr_sum = minn + second_minn

            # Update the maximum sum if the current sum is greater
            max_sum = max(max_sum, curr_sum)

    # Return the maximum sum found
    return max_sum


# Driver code
if __name__ == "__main__":
    arr = [4, 3, 1, 5, 6]
    result = find_max_sum(arr)

    # Output the result
    print(result)
C#
using System;
using System.Collections.Generic;

public class CircularPrimeChecker {
    // Function to find the maximum sum of the smallest and
    // second smallest numbers
    public static long FindMaxSum(List<int> arr)
    {
        int n = arr.Count;

        // Variable to store the maximum sum found
        long maxSum = 0;

        // Iterate over each element in the array except the
        // last one
        for (int i = 0; i < n - 1; i++) {
            // Initialize the minimum element as the current
            // element
            int minn = arr[i];

            // Initialize the second minimum element as the
            // next element
            int secondMinn = arr[i + 1];

            // Iterate over the remaining elements in the
            // array
            for (int j = i + 1; j < n; j++) {
                // Update the minimum and second minimum
                // elements
                if (minn >= arr[j]) {
                    secondMinn = minn;
                    minn = arr[j];
                }
                else if (secondMinn > arr[j]) {
                    secondMinn = arr[j];
                }

                // Calculate the current sum of the minimum
                // and second minimum elements
                long currSum = minn + secondMinn;

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

        // Return the maximum sum found
        return maxSum;
    }

    // Driver code
    public static void Main(string[] args)
    {
        List<int> arr = new List<int>{ 4, 3, 1, 5, 6};
        long result = FindMaxSum(arr);

        // Output the result
        Console.WriteLine(result);
    }
}
JavaScript
// Function to find the maximum sum of the
// smallest and second smallest numbers
function findMaxSum(arr) {
    const n = arr.length;

    // Variable to store the maximum sum found
    let maxSum = 0;

    // Iterate over each element in the array
    // except the last one
    for (let i = 0; i < n - 1; i++) {

        // Initialize the minimum element as
        // the current element
        let minn = arr[i];

        // Initialize the second minimum element
        // as the next element
        let secondMinn = arr[i + 1];

        // Iterate over the remaining elements
        // in the array
        for (let j = i + 1; j < n; j++) {
        
            // Update the minimum and second minimum
            // elements
            if (minn >= arr[j]) {
                secondMinn = minn;
                minn = arr[j];
            } else if (secondMinn > arr[j]) {
                secondMinn = arr[j];
            }

            // Calculate the current sum of the
            // minimum and second minimum elements
            let currSum = minn + secondMinn;

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

    // Return the maximum sum found
    return maxSum;
}

// Driver code
const arr = [4, 3, 1, 5, 6];
const result = findMaxSum(arr);

// Output the result
console.log(result);

Output
11

Time Complexity: O(n2), where n is the length of given array
Auxiliary Space: O(1)  

[Expected Approach] By maximizing consecutive element sum – O(n) time and O(1) auxiliary space

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 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.

Code Implementation:

CPP
// 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 methods
int main()
{
    int arr[] = {4, 3, 1, 5, 6};
    int N = sizeof(arr) / sizeof(int);

    cout << pairWithMaxSum(arr, N) << endl;
    return 0;
}
JAVA
// Java program to get max sum with smallest
// and second smallest element from any subarray
import 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 program
    public static void main(String[] args)
    {
        int arr[] = { 4, 3, 1, 5, 6 };
        int N = arr.length;
        System.out.println(pairWithMaxSum(arr, N));
    }
}
Python
# 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 subarrays 
def 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 code
arr = [4, 3, 1, 5, 6] 
N = len(arr)

print(pairWithMaxSum(arr, N)) 
C#
// C# program to get max sum with smallest
// and second smallest element from any subarray
using System;

class GFG {

    // 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 code
    public static void Main()
    {
        int[] arr = { 4, 3, 1, 5, 6 };
        int N = arr.Length;
        Console.Write(pairWithMaxSum(arr, N));
    }
}
JavaScript
// 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;
    console.log(pairWithMaxSum(arr, N));
PHP
<?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);

?>

Output
11

Time Complexity: O(n), where n is the length of given array
Auxiliary Space: O(1)
 



Next Article
Article Tags :
Practice Tags :

Similar Reads