java – Implementation of MinMax problems

Problem Statement:

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 injustice is minimized. Call that subarr matrix.

The injustice of a matrix is ​​calculated as: max (subarr) – min (subarr)

Where:

  • max denotes the largest integer in subarr
  • min denotes the smallest integer in subarr

Complete the maxMin function in the editor below. You must return an integer that denotes the minimum possible value of injustice.

Solution:

    static int maxMin (int k, int[] arr) {
int arrLen = arr.length;
Arrays.sort (arr);
In t[] subArr = Arrays.copyOfRange (arr, 0, k);
int minUnfairness = subArr[k - 1] - subArr[0];

for (int j = 1; j <arrLen - k + 1; j ++) {

subArr = Arrays.copyOfRange (arr, j, j + k);

int tempMinUnfairness = subArr[ k - 1 ] - subArr[0];

if (tempMinUnfairness <minUnfairness) {
Minerfairness = tempMinUnfairness;
}
}

back Minairairness;
}

/ **
* Valid test case for reference
* /
private static void validTest () {
In t[] arr = {10,100,300,200,1000,20,30}};
int = 20 is expected;
result int = maxMin (3, arr);
affirm (result == expected);
}

The main function to review is maxMin ().

We await your comments in –

  1. What other improvements can be made?
  2. What other forms could be there for the problem, like the current one
    Focus is greedy?

Thank you.