Longest subarray in which all elements are smaller than K | C ++ program for the above approach ; Function to find the length of the longest subarray with all elements smaller than K ; Stores the length of maximum consecutive sequence ; Stores maximum length of subarray ; Iterate through the array ; Check if array element smaller than K ; Store the maximum of length and count ; Reset the counter ; Print the maximum length ; Driver Code ; Given array arr [ ] ; Size of the array ; Given K ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int largestSubarray ( int arr [ ] , int N , int K ) { int count = 0 ; int len = 0 ; for ( int i = 0 ; i < N ; i ++ ) { if ( arr [ i ] < K ) { count += 1 ; } else { len = max ( len , count ) ; count = 0 ; } } if ( count ) { len = max ( len , count ) ; } cout << len ; } int main ( ) { int arr [ ] = { 1 , 8 , 3 , 5 , 2 , 2 , 1 , 13 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int K = 6 ; largestSubarray ( arr , N , K ) ; return 0 ; }