Was it helpful?

Question


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
raja
Published on 09-Sep-2020 13:20:03

Was it helpful?
Not affiliated with Tutorialspoint
scroll top