Stack is used to find the next larger element and keeps track of index of current iteration
while ( stk . length != 0 && arr [ i ] > arr [ stk [ stk . length - 1 ] ] ) { maxarr [ stk [ stk . length - 1 ] ] = i - 1 ; stk . pop ( ) ; } stk . push ( i ) ; }