
- 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 partitions of maximum size 2 and sum limited by given value in C++
Problem statement
Given an array arr[] of positive numbers, find minimum number of sets in array which satisfy following property,
- A set can contain maximum two elements in it. The two elements need not to be contiguous.
- Sum of elements of set should be less than or equal to given Key. It may be assumed that given key is greater than or equal to the largest array element.
Example
If arr[] = {1, 2, 3, 4} and k = 5 then following 2 pairs can be created −
{1, 4} and {2, 3}
Algorithm
- Sort the array
- Begin two pointers from two corners of the sorted array. If their sum is smaller than or equal to given key, then we make set of them, else we consider the last element alone
Example
#include <iostream> #include <algorithm> using namespace std; int getMinSets(int *arr, int n, int key) { int i, j; sort (arr, arr + n); for (i = 0, j = n - 1; i <= j; ++i) { if (arr[i] + arr[j] <= key) { --j; } } return i; } int main() { int arr[] = {1, 2, 3, 4}; int key = 5; int n = sizeof(arr) / sizeof(arr[0]); cout << "Minimum set = " << getMinSets(arr, n, key) << endl; return 0; }
Output
When you compile and execute above program. It generates following output −
Minimum set = 2
- Related Articles
- Maximum size subset with given sum in C++
- Find maximum (or minimum) sum of a subarray of size k in C++
- Maximum sum two non-overlapping subarrays of given size in C++
- Find maximum of minimum for every window size in a given array in C++
- Print maximum sum square sub-matrix of given size in C Program.
- Get maximum and minimum value in MongoDB?
- Getting Minimum and Maximum Value in MySQL
- Minimum Size Subarray Sum in C++
- Greatest sum of average of partitions in JavaScript
- Product of all Subsequences of size K except the minimum and maximum Elements in C++
- Path With Maximum Minimum Value in Python
- Display the minimum and maximum value of primitive data types in Java
- Maximum Size Subarray Sum Equals k in C++
- Maximum and Minimum element of a linked list which is divisible by a given number k in C++
- Finding the minimum and maximum value from a string with numbers separated by hyphen in MySQL?

Advertisements