# Max Min HackerRank Solution

In this Max Min HackerRank solution, You will be given a list of integers, , and a single integer . You must create an array of length  from elements of  such that its unfairness is minimized. Call that array . Unfairness of an array is calculated as

Where:
max denotes the largest integer in
min denotes the smallest integer in

Example

Pick any two elements, say .

Testing for all pairs, the solution  provides the minimum unfairness.

Note: Integers in  may not be unique.

Function Description

Complete the maxMin function in the editor below.
maxMin has the following parameter(s):

• int k: the number of elements to select
• int arr[n]:: an array of integers

Returns

• int: the minimum possible unfairness

Input Format

The first line contains an integer , the number of elements in array .
The second line contains an integer .
Each of the next  lines contains an integer  where .

Constraints

Sample Input

Sample Input #01

10
4
1
2
3
4
10
20
30
40
100
200


Sample Output

Sample Output #01

3


Explanation

Explanation #01
Here; selecting theintegers, unfairness equals

max(1,2,3,4) - min(1,2,3,4) = 4 - 1 = 3

## Max Min HackerRank Solution

I will Provide solution in Multiple programming languages for you. If you are not able to find the code in required language then please share in comments so that our team can help you.

### Problem Solution in PHP

function maxMin($k,$arr) {
rsort($arr);$unfair = $arr[0] -$arr[$k-1] ;$count = count($arr); for($i=0; $i<=$count-$k;$i++){
$min =$arr[$i] -$arr[$i + ($k - 1)];
if($min <$unfair){
$unfair =$min;
}
}

return \$unfair;
}

### Problem Solution in JavaScript

function maxMin(k, arr) {
arr.sort((a, b) => a - b);
const n = arr.length;
if (k >= n) return arr[n - 1] - arr[0];

let unfairness = arr[k - 1] - arr[0];
for (let i = 1; i < n; i++) {
if (arr[k - 1 + i] - arr[i] < unfairness) {
unfairness = arr[k - 1 + i] - arr[i];
}
}
return unfairness;
}

### Problem Solution in Python

def maxMin(k, arr):
# Write your code here
arr.sort()
res = []
index = 0
print(arr)
for i in range(len(arr)):
if(i+k<=len(arr)):
res.append(arr[i+k-1]-arr[i])
return min(res)

### Problem Solution in Java

    public static int maxMin(int k, List<Integer> arr) {
// Write your code here
List<Integer> res = new ArrayList<Integer>();
Collections.sort(arr);
for(int i=0; i<arr.size(); i++)
{
if(i+k<=arr.size()){
int value = arr.get(i+k-1)-arr.get(i);
}
}
return Collections.min(res);

}

### Problem Solution in C++

int maxMin(int k, vector<int> arr) {
sort(arr.begin(), arr.end());
int min = numeric_limits<int>::max();
for (int i = 0; i < arr.size() - k + 1; i++)
{
if (arr[k - 1 + i] - arr[i] < min)
min = arr[k - 1 + i] - arr[i];
}
return min;
}
Solve original Problem on HackerRank here. Checkout more HackerRank Problems