Count subarrays consisting of first K natural numbers in descending order | C ++ program for the above approach ; 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
#include <bits/stdc++.h> NEW_LINE using namespace std ; int CountSubarray ( int arr [ ] , int n , int k ) { int temp = k , count = 0 ; for ( int 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 ; } int main ( ) { int arr [ ] = { 1 , 2 , 3 , 7 , 9 , 3 , 2 , 1 , 8 , 3 , 2 , 1 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int K = 3 ; cout << CountSubarray ( arr , N , K ) ; return 0 ; }