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.
Examples:
Input: arr[] = [10, 20, 12], key = 25
Output: 2
We break into two parts {10, 12} and {2}
Input : arr[] = [3, 5, 3, 4], key=5
Output : 4
Explanation: 4 sets (3), (5), (3), (4)
The idea is to first sort the array, then follow two pointer approach. We 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.
Below is the implementation of the above approach :
C++
#include <algorithm>
#include <iostream>
using namespace std;
int minimumSets( 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[] = { 3, 5, 3, 4 };
int n = sizeof (arr) / sizeof (arr[0]);
int key = 5;
cout << minimumSets(arr, n, key);
return 0;
}
|
Java
import java.util.Arrays;
class GFG {
static int minimumSets( int arr[], int n, int key)
{
int i, j;
Arrays.sort(arr);
for (i = 0 , j = n - 1 ; i <= j; ++i)
if (arr[i] + arr[j] <= key)
j--;
return i;
}
public static void main (String[] args) {
int []arr = { 3 , 5 , 3 , 4 };
int n =arr.length;
int key = 5 ;
System.out.println( minimumSets(arr, n, key));
}
}
|
Python3
def minimumSets(arr, n, key):
arr.sort(reverse = False )
j = n - 1
for i in range ( 0 , j + 1 , 1 ):
if (arr[i] + arr[j] < = key):
j - = 1
return i + 1
if __name__ = = '__main__' :
arr = [ 3 , 5 , 3 , 4 ]
n = len (arr)
key = 5
print (minimumSets(arr, n, key))
|
C#
using System;
class GFG
{
static int minimumSets( int []arr,
int n, int key)
{
int i, j;
Array.Sort(arr);
for (i = 0, j = n - 1; i <= j; ++i)
if (arr[i] + arr[j] <= key)
j--;
return i;
}
public static void Main ()
{
int []arr = { 3, 5, 3, 4 };
int n =arr.Length;
int key = 5;
Console.WriteLine(minimumSets(arr, n, key));
}
}
|
PHP
<?php
function minimumSets( $arr , $n , $key )
{
$i ; $j ;
sort( $arr );
for ( $i = 0, $j = $n - 1; $i <= $j ; ++ $i )
if ( $arr [ $i ] + $arr [ $j ] <= $key )
$j --;
return $i ;
}
$arr = array ( 3, 5, 3, 4 );
$n = count ( $arr );
$key = 5;
echo minimumSets( $arr , $n , $key );
?>
|
Javascript
<script>
function minimumSets(arr, n, key)
{
var i, j;
arr.sort((a,b)=> a-b)
for (i = 0, j = n - 1; i <= j; ++i)
if (arr[i] + arr[j] <= key)
j--;
return i;
}
var arr = [3, 5, 3, 4];
var n = arr.length;
var key = 5;
document.write( minimumSets(arr, n, key));
</script>
|
Complexity Analysis:
- Time complexity: O(nlogn)
- Auxiliary Space: O(1)