Number of valid indices in the permutation of first N natural numbers | Function to return the number of i 's such that Pi <= Pj for all 1 <= j <= i in the permutation of first N natural numbers ; To store the count of such indices ; Store the mini value ; For all the elements ; Return the required answer ; Driver code
function min_index ( p , n ) { let ans = 0 ; let mini = Number . MAX_SAFE_INTEGER ; for ( let i = 0 ; i < n ; i ++ ) { if ( p [ i ] <= mini ) mini = p [ i ] ; if ( mini == p [ i ] ) ans ++ ; } return ans ; } let P = [ 4 , 2 , 5 , 1 , 3 ] ; let n = P . length ; document . write ( min_index ( P , n ) ) ;