How to Solve Max-Min Arrays in Java

The challenge

You are given an array of unique elements, and your task is to rearrange the values so that the first max value is followed by the first minimum, followed by second max value then second min value, etc.

For example:

solve([15,11,10,7,12]) = [15,7,12,10,11]

The first max is 15 and the first min is 7. The second max is 12 and the second min is 10 and so on.

The solution in Java code

Option 1:

import java.util.*; class Solution{ public static int[] solve (int[] arr){ Arrays.sort(arr); int[] solutionArray = new int[arr.length]; for(int i = 0; i < arr.length; i++){ solutionArray[i] = i % 2 == 0 ? arr[arr.length - i/2 - 1] : arr[i/2]; } return solutionArray; } }
Code language: Java (java)

Option 2:

import java.util.*; class Solution{ public static int[] solve (int[] arr){ List<Integer> temp = new ArrayList<Integer>(); Arrays.sort(arr); for (int i = 0, j = arr.length - 1; i <= j; ++i, --j) { if (i != j) temp.add(arr[j]); temp.add(arr[i]); } return temp.stream().mapToInt(i -> i).toArray(); } }
Code language: Java (java)

Option 3:

import java.util.stream.IntStream; class Solution { public static int[] solve(int[] arr) { int[] sorted = IntStream.of(arr).sorted().toArray(); int[] result = new int[arr.length]; for (int i = 0, j = arr.length - 1, f = -1; i < arr.length;) { result[i] = sorted[j]; j = (j + arr.length + (f *= -1) * (++i)) % arr.length; } return result; } }
Code language: Java (java)

Test cases to validate our solution

import org.junit.Test; import static org.junit.Assert.assertArrayEquals; import org.junit.runners.JUnit4; public class SolutionTest{ @Test public void basicTests(){ assertArrayEquals(new int[]{15,7,12,10,11},Solution.solve(new int[]{15,11,10,7,12})); assertArrayEquals(new int[]{15,7,12,10,11},Solution.solve(new int[]{15,11,10,7,12})); assertArrayEquals(new int[]{15,7,12,10,11},Solution.solve(new int[]{15,11,10,7,12})); } }
Code language: Java (java)
Tags:
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments