It was a question, I was asked in an interview.
What is the best time complexity you can find to find the minimum and maximum array?
I replied: O (n). Iterate through the array, tracking the max and min found so far. very simple and direct.
The interviewer asked if you could improve it using split and win. I said probably not. Then the conversation continued, and finally, I was asked to implement the βdivideβ and βwinβ approach.
There he is:
public class MinMaxInArray {
public static int[] findMinMax(int[] array, int i, int j){
int arrLen = j - i + 1;
if (arrLen == 1)
return new int[]{array[i], array[j]};
if (arrLen == 2){
int min = Math.min(array[i], array[j]);
int max = Math.max(array[i], array[j])
return new int[]{min, max};
}
int mid = i + (j-i)/2;
int[] leftMinMax = findMinMax(array, i, mid);
int[] rightMinMax = findMinMax(array, mid+1, j);
return new int[]{ Math.min(leftMinMax[0], rightMinMax[0]), Math.max(leftMinMax[1], rightMinMax[1]) };
}
public static void main(String[] args){
int[] array = {20, 5, 7, 25, 30, 1, 9, 12};
int[] minMax= findMinMax(array, 0, array.length - 1);
System.out.println("min = " + minMax[0] + ", max = " + minMax[1] );
}
}
, O (n), . , O (log n), . , , O (n). divide conquer , .
, , , O (n).