JAVA PROGRAM TO FIND THE MAXIMUM AND MINIMUM ELEMENT IN AN ARRAY

 

 

An  array  of  integers  arr[]  , find  the  maximum  and   minimum   elements  in  the  array.

 

Examples:

 

Input :  arr[] =[5,9,15,3,65,35];

 

Output :   [3 , 65 ]

 

Explanation :  The  minimum  element  is  3  and  the  maximum  element  is  65.

 

 

 

The  best  approach  to  find  the  maximum  and  minimum   element  in  an  array  is  to  iterate  through  the  array   by  maintaining  two  variables  to  track  the  maximum  and  minimum  element   and  so  far .

 

 

 

 

 

import  java.util.Arrays;

public   class    MaxMinArray {

 

    public  static   void  main(String  args[]){

    int [ ]     numbers = { 88, 35, 45 ,99, 78};

 

//Edge  case  check  for  empty  array

 

    if ( numbers==null  || numbers.length==0 )  {

       System.out.ptrintln(“Array  is  Empty”);

        return;

         }

// Initialize    variable  max  and  min  with   the  first  element  of  the  array

      int   max =   numbers[0] ;

      int     min=numbers[0];

   //Iterate  through  the   array  starting  from  the  second   element

     for  (int  i=1 ;  i<numbers.length ; i++ )  {

     if ( numbers[i] > max )  {

          max=numbers[i]; //update  the   maximum

      }

      else  if  (numbers[i] < min ) {

        min=numbers[i]; //update  minimum

       }

    }

 

    System.out.println(“Original  Array:”+Arrays.toString(numbers));

    System.out.println(“Maximum  Element  is  : “  + max);

    System.out.println(“Minimum  Element  is” +min);

  }

  }

     }

 

 

   

 

 

Approach 2:

 

 Using  Java 8  Streams

 

 

import  java.util.Arrays ;

 public  class  MaxMinArr{

    public  static  void  main(String  args[] ) {

    int []  numbers =  { 35,66,88,55,49 };

      //Find  the  max  and  min  using  built-in  Stream  methods

       int  max=Arrays.stream(numbers).max() .getAsInt();

 int   min =  Arrays.stream(numbers).min().getAsInt();

   

  System.out.println(“Maximum  element  is : “  + max);

  System.out.println(“Minimum  element  is  : “ + min);

 

}

}

 

 

     

Leave a Comment

Your email address will not be published. Required fields are marked *