Previous greater element | Java program previous greater element A naive solution to print previous greater element for every element in an array . ; Previous greater for first element never exists , so we print - 1. ; Let us process remaining elements . ; Find first element on left side that is greater than arr [ i ] . ; If all elements on left are smaller . ; Driver Code
import java . io . * ; import java . util . * ; import java . lang . * ; class GFG { static void prevGreater ( int arr [ ] , int n ) { System . out . print ( " - 1 , ▁ " ) ; for ( int i = 1 ; i < n ; i ++ ) { int j ; for ( j = i - 1 ; j >= 0 ; j -- ) { if ( arr [ i ] < arr [ j ] ) { System . out . print ( arr [ j ] + " , ▁ " ) ; break ; } } if ( j == - 1 ) System . out . print ( " - 1 , ▁ " ) ; } } public static void main ( String [ ] args ) { int arr [ ] = { 10 , 4 , 2 , 20 , 40 , 12 , 30 } ; int n = arr . length ; prevGreater ( arr , n ) ; } }