Using divide & conquer improves the time complexity to find max and min in an array

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){
        // base cases
        int arrLen = j - i + 1;
        if (arrLen == 1)
            return new int[]{array[i], array[j]};    //j and i are the same

        if (arrLen == 2){
            int min = Math.min(array[i], array[j]);
            int max = Math.max(array[i], array[j])           
            return new int[]{min, max};
        }

        // actual divide and conquer        
        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);           //minMax[0] = minimum value, minMax[1] = maximum value
        System.out.println("min = " + minMax[0] + ", max = " + minMax[1] );
    }

}

, O (n), . , O (log n), . , , O (n). divide conquer , .

, , , O (n).

+4
2

. , ( , ).

, O (log N), - (, ), , , - .

, , min max O (1), , .

, -- , . , , O (log N), , , , , , , .

+6

, min max O (n).

divide , , .

, divide conquer 3/2n -2, n 2. , 3/2n -2 , n 2.

0

Source: https://habr.com/ru/post/1570428/


All Articles