# Maximum sum of smallest and second smallest in an array in C++ Program

C++Server Side ProgrammingProgramming

In this problem, we are given an array arr[]. Our task is to create a program to find the maximum sum of smallest and second smallest in an array.

Problem Description − We need to find the sum of the smallest and second smallest elements of a sum subarray of the array. And return the maximum of all such subarray sums.

## Example

Let’s take an example to understand the problem,

## Input

arr[] = {3, 5, 4, 2, 9, 1, 6}

## Output

11

## Explanation

Their out of all subarrays possible,
{2, 9} has a maximum sum of smallest elements.
Sum = 2 + 9 = 11

## Solution Approach

A simple solution to the problem is by generating all subarrays. Find the smallest and second smallest element, find sum. Return the maximum sum of all.

Another more efficient solution is based on the observation of examples. We need to find the maximum sum which will be the sum of two consecutive element pairs of the array. And we will find the maximum sum pair.

## Algorithm

Initialize

maxSum = −1

Step 1

loop i −> 0 to n−1

Step 1.1

if maxSum < (arr[i] + arr[i+1]). Then, maxSum = (arr[i] +
arr[i+1])

Step 2

Return maxSum.

## Example

Program to illustrate the working of our solution,

Live Demo

#include <iostream>
using namespace std;
int calcMaxSumPairs(int arr[], int n) {
int maxSum = −1;
for (int i=0; i< (n − 1); i++)
if(maxSum < (arr[i] + arr[i + 1]))
maxSum = (arr[i] + arr[i + 1]);
return maxSum;
}
int main() {
int arr[] = {3, 4, 2, 9, 5, 6};
int n = sizeof(arr) / sizeof(int);
cout<<"The maximum sum of smallest and second smallest in an
array is "<<calcMaxSumPairs(arr, n);
return 0;
}

## Output

The maximum sum of smallest and second smallest in an array is 14