Monday 6 June 2016

Find the Leaders in an array

An element is leader if it is greater than all the elements to its right side.

Example: Leaders in the array {18, 19, 7, 4, 6, 2} are 2, 6, 7 and 19.
 
public class LeadersInArray {
     public static void main(String[] args) {
           int[] array = {18, 19, 7, 4, 6, 2};
 
           int max = Integer.MIN_VALUE;
 
           for(int i=array.length-1;i>=0;i--) {
                if(array[i]>max) {
                     System.out.print(array[i]+" ");
                     max = array[i];
                }
           }
     }
}

No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...