Minimum value of “max + min” in a subarray in C++

C++Server Side ProgrammingProgramming

Problem statement

Given a array of n positive elements we need to find the lowest possible sum of max and min elements in a subarray given that size of subarray should be greater than equal to 2.

Example

If arr[] = {10, 5, 15, 7, 2, 1, 3} then sum of “max + min” is 3 when we add “2 + 1”.

Algorithm

  • Adding any element to a subarray would not increase sum of maximum and minimum.
  • Since the max of an array will never decrease on adding elements to the array. It will only increase if we add larger elements. So it is always optimal to consider only those subarrays having length 2.
  • Hence consider all subarrays of length 2 and compare sum and take the minimum one.

Example

 Live Demo

#include <bits/stdc++.h>
using namespace std;
int getMaxSum(int *arr, int n) {
   if (n < 2) {
      return -1;
   }
   int result = arr[0] + arr[1];
   for (int i = 1; i + 1 < n; ++i) {
      result = min(result, (arr[i] + arr[i + 1]));
   }
   return result;
}
int main() {
   int arr[] = {10, 5, 15, 7, 2, 1, 3};
   int n = sizeof(arr) / sizeof(arr[0]);
   cout << "Maximum sum = " << getMaxSum(arr, n) << endl;
   return 0;
}

When you compile and execute above program. It generates following output −

Output

Maximum sum = 3
raja
Published on 20-Dec-2019 14:43:53
Advertisements