Count subarrays consisting of first K natural numbers in descending order | Function to count subarray having the decreasing sequence K to 1 ; Traverse the array ; Check if required sequence is present or not ; Reset temp to k ; Return the count ; Driver Code ; Function Call
function CountSubarray ( arr , n , k ) { var temp = k , count = 0 ; for ( var i = 0 ; i < n ; i ++ ) { if ( arr [ i ] == temp ) { if ( temp == 1 ) { count ++ ; temp = k ; } else temp -- ; } else { temp = k ; if ( arr [ i ] == k ) i -- ; } } return count ; } var arr = [ 1 , 2 , 3 , 7 , 9 , 3 , 2 , 1 , 8 , 3 , 2 , 1 ] ; var N = arr . length ; var K = 3 ; document . write ( CountSubarray ( arr , N , K ) ) ;