Saturday, December 9, 2023
HomeSoftware EngineeringLearn how to Remedy Max-Min Arrays in Java

# Learn how to Remedy Max-Min Arrays in Java

## The problem#

You’re given an array of distinctive components, and your activity is to rearrange the values in order that the primary max worth is adopted by the primary minimal, adopted by second max worth then second min worth, and so on.

For instance:

``````resolve([15,11,10,7,12]) = [15,7,12,10,11]
``````

The primary max is `15` and the primary min is `7`. The second max is `12` and the second min is `10` and so forth.

## The answer in Java code#

Possibility 1:

``````import java.util.*;

public static int[] resolve (int[] arr){
Arrays.kind(arr);
int[] solutionArray = new int[arr.length];

for(int i = 0; i < arr.size; i++){
solutionArray[i] = i % 2 == 0 ? arr[arr.length - i/2 - 1] : arr[i/2];
}
return solutionArray;
}
}
``````

Possibility 2:

``````import java.util.*;

public static int[] resolve (int[] arr){
Listing<Integer> temp = new ArrayList<Integer>();
Arrays.kind(arr);
for (int i = 0, j = arr.size - 1; i <= j; ++i, --j) {
}
return temp.stream().mapToInt(i -> i).toArray();
}
}
``````

Possibility 3:

``````import java.util.stream.IntStream;

public static int[] resolve(int[] arr) {
int[] sorted = IntStream.of(arr).sorted().toArray();
int[] end result = new int[arr.length];
for (int i = 0, j = arr.size - 1, f = -1; i < arr.size;) {
end result[i] = sorted[j];
j = (j + arr.size + (f *= -1) * (++i)) % arr.size;
}
return end result;
}

}
``````

## Check instances to validate our answer#

``````import org.junit.Check;
import static org.junit.Assert.assertArrayEquals;
import org.junit.runners.JUnit4;

public class SolutionTest{
@Check
public void basicTests(){
}
}
``````
RELATED ARTICLES