Home > OS >  Find min 3 values and max 3 values in array in Java
Find min 3 values and max 3 values in array in Java

Time:10-14

I have a problem about finding 3 min values and 3 max values in the number array. Even if I correctly find all these 3 max values in the array, I couldn't get the min3 value.

min3 is normally -1, but I get 4.

How can I fix it?

Here is the code snippet shown below.

int max1 = Integer.MIN_VALUE;
int max2 = Integer.MIN_VALUE;
int max3 = Integer.MIN_VALUE;
        
int min1 = Integer.MAX_VALUE;
int min2 = Integer.MAX_VALUE;
int min3 = Integer.MAX_VALUE; 
        
if(nums.length >= 3) {
            
    for(Integer value : nums) {
        int current = value;
                
                
        // Max
        if(current > max1) {
            max3 = max2;
            max2 = max1;
            max1 = current;
        }else if(current > max2){
            max3 = max2;
            max2 = current;
        }else {
            max3 = current;
        }
                
        // min
        if(min1 > current) {
            min3 = min2;
            min2 = min1;
            min1 = current;
        }
        else if(min2 > current) {
            min3 = min2;
            min2 = current; 
        }else {
            min3 = current; 
        }
                
    }
            
    System.out.println("max1 : "   max1   " , max2 : "   max2   " , max3 : "   max3);
    System.out.println("min1 : "   min1   " , min2 : "   min2   " , min3 : "   min3);
                
}

Here is the console output shown below.

max1 : 4 , max2 : 3 , max3 : 2
min1 : -100 , min2 : -98 , min3 : 4

CodePudding user response:

You don't check if current < min3

CodePudding user response:

Solution for the problem "find N max / N min" based on N variables and manually implemented conditional logic is inflexible and can be error-prone.

If you need to find, let's say, 10 min/max values instead of 3 it would become totally unmanageable.

Instead of the swarm of variable, you can maintain two PriorityQueues. Before adding attempting to add a new element to the queue you would need to check it its size and compare the next element against the root-element of the queue.

That's how it might be implemented:

public static void main(String[] args) {
    int[] arr = {8, 5, 7, 8, -3, 5, -5, 9, 12, 18};

    Queue<Integer> min = new PriorityQueue<>(Comparator.reverseOrder());
    Queue<Integer> max = new PriorityQueue<>();
    
    for (int next: arr) {
        tryAdd(min, 3, next);
        tryAdd(max, 3, next);
    }

    System.out.println(min);
    System.out.println(max);
}

Output:

[18, 5, 7]
[9, 12, 18]
  • Related