Maximum sum of smallest and second smallest in an array in C++
https://www.tutorialspoint.com/maximum-sum-of-smallest-and-second-smallest-in-an-array-in-cplusplus
-
10-09-2020 - |
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
#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
Not affiliated with Tutorialspoint