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


In this tutorial, we will be discussing a program to find maximum sum of smallest and second smallest in an array.

For this we will be provided with an array containing integers. Our task is to find the maximum sum of smallest and second smallest elements in every possible iteration of array.

Example

 Live Demo

#include <bits/stdc++.h>
using namespace std;
//returning maximum sum of smallest and
//second smallest elements
int pairWithMaxSum(int arr[], int N) {
   if (N < 2)
      return -1;
   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() {
   int arr[] = {4, 3, 1, 5, 6};
   int N = sizeof(arr) / sizeof(int);
   cout << pairWithMaxSum(arr, N) << endl;
   return 0;
}

Output

11

Updated on: 09-Sep-2020

81 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements