Programmerabc
Programmerabc

Reputation: 327

Optimization for finding Leader numbers of an array

I am trying to write a program which finds Leader Numbers in an array.There are certain time constraints and the code is failing to meet them.Any possible suggestion for code optimization to meet those constrains. If possible, please provide a code snippet.

Leader Number : An element is a leader if it is greater than all the elements to its right side

Code:

static ArrayList<Integer> leaders(int arr[], int n){
        ArrayList<Integer> arrlst = new ArrayList<Integer>();
        int highest_val = arr[n-1];
        arrlst.add(highest_val);
        for(int i=n-2;i>-1;i--)
        {
            if(arr[i]>=highest_val){
                highest_val = arr[i];
                arrlst.add(0, highest_val);
            }
        }
        return arrlst;
    }

Upvotes: 0

Views: 72

Answers (1)

Valerij Dobler
Valerij Dobler

Reputation: 2764

You are adding the new highest at index 0, hence you always shift down all previous leaders by one. Maybe add them at the end and reverse the list at the end instead?

Upvotes: 1

Related Questions