
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
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 Articles
- Sorting max to min value in MySQL
- Minimum removals from array to make max – min
- Min-Max Range Queries in Array in C++
- How to define a MIN and MAX value for EditText in Android?
- Python - Assign a specific value to Non Max-Min elements in Tuple
- Minimum element in a max heap in C++.
- Convert min Heap to max Heap in C++
- max() and min() in Python
- Minimum Size Subarray Sum in C++
- Use of min() and max() in Python
- Create a vertical slider with custom min, max, and initial value in Java
- How to SELECT min and max value from the part of a table in MySQL?
- Min-Max Heaps
- How to define a MIN and MAX value for EditText in Android using Kotlin?
- How to create a horizontal slider with custom min, max, and initial value in Java

Advertisements