Close

Printing biggest elements to its right in an array

Given array of elements we have to write a program to print the biggest element to it’s right for each of the elements in the given array.

For example let us consider the array {3, 9, 2, 4, 6, 1}.

The output for this array should be {9, 6, 6, 6, 1, -1}. As a convention, we print -1 for the last element because there are no elements to it’s right.

This problem can be solved in O(n) time and O(1) space by using the following algorithm.

Start from the end of the array. print -1 for the last element. Use a variable to keep track of the greatest element found so far while traversing backwards and fill the entries with this variable.

Here is the Java program to do this.

Leave a Reply

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