You will be given a list of integers, arr, and a single integer k. You must create an array of length k from elements of arr such that its unfairness is minimized. Call that array arr'. The unfairness of an array is calculated as
max(arr')-min(arr')
where:
- max denotes the largest integer in arr'
- min denotes the smallest integer in arr'
- min denotes the smallest integer in arr'
Example:
Input: n = 10, k = 4,arr[] = {1, 2, 3, 4, 10, 20, 30, 40, 100, 200}
Output: 3
Approach
Java
import java.util.Arrays;public class MaxMin {public static void main(String[] args) {int n = 10, k = 4;int arr[] = { 1, 2, 3, 4, 10, 20, 30, 40, 100, 200 };Arrays.sort(arr);int min1 = arr[0];int max1 = arr[k - 1];int ans = max1 - min1;for (int i = k; i < n; i++) {max1 = arr[i];min1 = arr[i - k + 1];ans = Math.min(max1 - min1, ans);}System.out.println(ans);}}
C++
#include <bits/stdc++.h>using namespace std;int main(){int n = 10, k = 4;int arr[n] = {1, 2, 3, 4, 10, 20, 30, 40, 100, 200};sort(arr, arr + n);int min1 = arr[0];int max1 = arr[k - 1];int ans = max1 - min1;for (int i = k; i < n; i++){max1 = arr[i];min1 = arr[i - k + 1];ans = min(max1 - min1, ans);}cout << ans << "\n";return 0;}
No comments:
Post a Comment