 
  Data Structure Data Structure
 Networking Networking
 RDBMS RDBMS
 Operating System Operating System
 Java Java
 MS Excel MS Excel
 iOS iOS
 HTML HTML
 CSS CSS
 Android Android
 Python Python
 C Programming C Programming
 C++ C++
 C# C#
 MongoDB MongoDB
 MySQL MySQL
 Javascript Javascript
 PHP PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Minimum value of “max + min” in a subarray in C++
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
#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
Advertisements
 