Finding the array with the lowest max value of element

Jane :

I have an arraylist of int[] arrays and I'm trying to find the array with the lowest max element.

For an example, from arrays [1,2,5], [0,1,2], [8,0,0] it would be the array [0,1,2] because the max element is 2.

However, my code is not working correctly. Could you help me fix my code? Thanks!

int min = Integer.MAX_VALUE;
for (int i=0; i<list.size(); i++) {
    for (int j=0; j<list.get(i).length; j++) {
        if (list.get(i)[j]<min) {
            min = list.get(i)[i]; 
            minIndex = i; //index of the array in arraylist
        }
    }
}
Eran :

Your code finds the lowest value across all arrays (at least it would if you fix the typo of list.get(i)[i] to list.get(i)[j]).

You should find the maximum element of each array, and then check if that maximum is smaller than all the previously found maximums:

int minIndex = 0;
int min = Integer.MAX_VALUE;
for (int i=0; i<list.size(); i++) {
    int max = Integer.MIN_VALUE;
    for (int j=0; j<list.get(i).length; j++) { // find max element of current array
        if (list.get(i)[j] > max) {
            max = list.get(i)[j]; 
            if (max > min) {
                break; // we already know the max of this array is not the smallest max
            }
        }
    }
    if (max < min) { // check if the max of the current array is the smallest max so far
        min = max;
        minIndex = i; //index of the array in arraylist
    }
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=146409&siteId=1