

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
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
- Related Questions & Answers
- Sorting max to min value in MySQL
- Min-Max Heaps
- Use of min() and max() in Python
- max() and min() in Python
- How to define a MIN and MAX value for EditText in Android?
- Python - Assign a specific value to Non Max-Min elements in Tuple
- Symmetric Min-Max Heaps
- How to SELECT min and max value from the part of a table in MySQL?
- Create a vertical slider with custom min, max, and initial value in Java
- Minimum removals from array to make max – min <= K in C++
- Average of array excluding min max JavaScript
- Min and max values of an array in MongoDB?
- How to define a MIN and MAX value for EditText in Android using Kotlin?
- Find Min-Max in heterogeneous list in Python
- Min-Max Range Queries in Array in C++
Advertisements