Wednesday, August 9, 2017

Leaders in an array Java Solution


 An element is leader if it is greater than all the elements to its right side. And the rightmost element is always a leader. For example int the array {16, 17, 4, 3, 5, 2}, leaders are 17, 5 and 2.

Sample Code:

/**
 *
 */
/**
 * @author Abhinaw.Tripathi
 *
 */
public class LeadersInArray
{

public void printLeaders(int arr[], int size)
    {
        for (int i = 0; i < size; i++)
        {
            int j;
            for (j = i + 1; j < size; j++)
            {
                if (arr[i] <= arr[j])
                    break;
            }
            if (j == size)
                System.out.print(arr[i] + " ");
        }
}

public void printLeadersMoreOptimized(int arr[], int size)
     {
       int max_from_right =  arr[size-1];
       System.out.print(max_from_right + " ");
   
       for (int i = size-2; i >= 0; i--)
       {
           if (max_from_right < arr[i])
           {          
             max_from_right = arr[i];
             System.out.print(max_from_right + " ");
           }
       }  
     }

public static void main(String[] args)
{
   LeadersInArray lead = new LeadersInArray();
       int arr[] = new int[]{16, 17, 4, 3, 5, 2};
       int n = arr.length;
       lead.printLeaders(arr, n);
     
     /*  LeadersInArray lead = new LeadersInArray();
       int arr[] = new int[]{16, 17, 4, 3, 5, 2};
       int n = arr.length;
       lead.printLeadersMoreOptimized(arr, n);*/
}
}

Output: 17 5 2

Time Complexity: O(n*n)

but if you use my 2nd method then time complexity will be reduced  to O(n).



No comments: