Joker Joker - 1 month ago 17
Java Question

Maximum minus minimum in an array

I am trying to find range(max - min) of an array using recursion.
Since, there can be only one return value, I am kind of confused how to go about this problem.
What I have done so far is to find maximum and minimum recursively using recursion and then use this in range function to find the range. I was wondering if it was possible to do everything in just range function somehow recursively. Following is my code-

public static int max(int[] array, int N) {
int maximum;

if (N >= array.length) {
maximum = Integer.MIN_VALUE;
} else {
maximum = max(array, N + 1);
if (array[N] > maximum) {
maximum = array[N];
}
}

return maximum;
}

public static int min(int[] array, int N) {
int minimum;

if (N >= array.length) {
minimum = Integer.MAX_VALUE;
} else {
minimum = min(array, N + 1);
if (array[N] < minimum) {
minimum = array[N];
}
}

return minimum;
}

public static int range(int [] array)
{
int max1 = max(array , 0);
System.out.println(max1);
int min1 = min(array , 0);
System.out.println(min1);
int range = max1 - min1;

return range;
}

Answer

If recursion really is a requirement, and you just need the range, then this should do it:

public static int range(int [] array, int index, int min, int max)
{
    if (index == array.length) {
        if (index == 0)
            return 0;
        else
            return max - min;
    }
    else {
        int value = array[index];
        return range(array, index + 1, Math.min(value, min), Math.max(value, max));
    }
}

public static int range(int [] array)
{
    return range(array, 0, Integer.MAX_VALUE, Integer.MIN_VALUE);
}