# Minimum partitions of maximum size 2 and sum limited by given value in C++

C++Server Side ProgrammingProgramming

<h2>Problem statement</h2><p>Given an array arr[] of positive numbers, find minimum number of sets in array which satisfy following property,</p><ul class="list"><li>A set can contain maximum two elements in it. The two elements need not to be contiguous.</li><li>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.</li></ul><h2>Example</h2><p>If arr[] = {1, 2, 3, 4} and k = 5 then following 2 pairs can be created &minus;</p><p>{1, 4} and {2, 3}</p><h2>Algorithm</h2><ul class="list"><li>Sort the array</li><li>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</li></ul><h2>Example</h2><pre class="prettyprint notranslate">#include &lt;iostream&gt; #include &lt;algorithm&gt; using namespace std; int getMinSets(int *arr, int n, int key) { &nbsp; &nbsp;int i, j; &nbsp; &nbsp;sort (arr, arr + n); &nbsp; &nbsp;for (i = 0, j = n - 1; i &lt;= j; ++i) { &nbsp; &nbsp; &nbsp; if (arr[i] + arr[j] &lt;= key) { &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;--j; &nbsp; &nbsp; &nbsp; } &nbsp; &nbsp;} &nbsp; &nbsp;return i; } int main() { &nbsp; &nbsp;int arr[] = {1, 2, 3, 4}; &nbsp; &nbsp;int key = 5; &nbsp; &nbsp;int n = sizeof(arr) / sizeof(arr); &nbsp; &nbsp;cout &lt;&lt; &quot;Minimum set = &quot; &lt;&lt; getMinSets(arr, n, key) &lt;&lt; endl; &nbsp; &nbsp;return 0; }</pre><h2>Output</h2><p>When you compile and execute above program. It generates following output &minus;</p><pre class="result notranslate">Minimum set = 2</pre>