Find the Max and Min element of an array

ยท

2 min read

OK so the question is to find the Maximum and the minimum element in a given array, the array is not sorted. So since the array is not sorted you cannot just pick the element at the last and first index, So how to do it.

How can we do it

We will first take two variables Min and Max, where we wil store the maximum and the minimum values. Initialy we can store the first element of the array in both variables or we can use Integer.MAX_VALUE and Integer.MIN_VALUE (in case of java). Now it's very simple, we will run a loop and compare each element with the Max variable to update the max value and each variable with the Min to update the min value. Its that simple.

Code in java

class Solution
{ 
    public static void findSum(int A[],int N) 
    {
        //code here
        int max=Integer.MIN_VALUE; //to store the Maximum value
        int min=Integer.MAX_VALUE; //to store the Minimum value
        for(int i=0;i<N;i++){
            //loop to check each value
            max=Math.max(max,A[i]); //This will give the maximum between max and A[i]
            min=Math.min(min,A[i]); ////This will give the minimum between min and A[i]
        }
        System.out.println("The Maximum is "+max);
        System.out.println("The Minimum is "+min);  
    }
}

Now one thing I would like to point is that initially we store Integer.MAX_VALUE in min and Integer.MIN_VALUE in max, let me explain it why. Initializing max to Integer.MIN_VALUE and min to Integer.MAX_VALUE is like starting with extreme values. These extreme values act as placeholders that guarantee any element in the array will be considered as an update for both max and min during the iteration.

  • max is set to the smallest possible integer initially. As you go through the array, if you find a number greater than the current max, you update max with that number.

  • min is set to the largest possible integer initially. As you go through the array, if you find a number smaller than the current min, you update min with that number.

This approach ensures that you start with values that are guaranteed to be surpassed by any valid element in the array for max, and any valid element in the array will be smaller than min. As you iterate through the array, these initial extreme values get replaced by the actual maximum and minimum values in the array.

So that was a pretty simple problem and I hope you undestood it. I hope you didn't had and problem but still you if you had you can ask me for any help. For more such tech content you can follow me on youtube and facebook. Till then keep learning and keep coding, Goodbye.

ย