java – Implementing the MinMax problem

Statement of the problem:

You will receive a list of integers, arr, and a single integer k.
You need to create an array of length k from arr items such as
his injustice is minimized. Call this subarr table.

The unfairness of a table is calculated as follows: max (subarr) – min (subarr)

Or:

  • max is the largest integer of subarr
  • min is the smallest integer of subarr

Fill the maxMin function in the editor below. It must return an integer indicating the minimum possible value of injustice.

Solution:

    static int maxMin (int k, int[] arr) {
int arrLen = arr.length;
Arrays.sort (arr);
int[] 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) {
minUnfairness = tempMinUnfairness;
}
}

back minUnfairness;
}

/ **
* Test case valid for reference
* /
void static private validTest () {
int[] arr = {10,100,300,200,1000,20,30};
int expected = 20;
int result = maxMin (3, arr);
assert (expected == result);
}

The main function to examine is maxMin ().

Looking forward to your comments on –

  1. What other improvements can be made?
  2. What other ways could be there for the problem, such as the current
    approach is greedy?

Thank you.