Number of valid indices in the permutation of first N natural numbers | C ++ implementation of the approach ; 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
#include <bits/stdc++.h> NEW_LINE using namespace std ; int min_index ( int p [ ] , int n ) { int ans = 0 ; int mini = INT_MAX ; for ( int i = 0 ; i < n ; i ++ ) { if ( p [ i ] <= mini ) mini = p [ i ] ; if ( mini == p [ i ] ) ans ++ ; } return ans ; } int main ( ) { int P [ ] = { 4 , 2 , 5 , 1 , 3 } ; int n = sizeof ( P ) / sizeof ( int ) ; cout << min_index ( P , n ) ; return 0 ; }