Check if a subarray of size K exists whose elements form a number divisible by 3 | C ++ implementation of the above approach ; Function to find the K size subarray ; Check if the first K elements forms a number which is divisible by 3 ; Using Sliding window technique ; Calculate sum of next K size subarray ; Check if sum is divisible by 3 ; Update the indices of the subarray ; If no such subarray is found ; Print the subarray ; Driver 's code ; Given array and K ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; void findSubArray ( vector < int > arr , int k ) { pair < int , int > ans ; int i , sum = 0 ; for ( i = 0 ; i < k ; i ++ ) { sum += arr [ i ] ; } int found = 0 ; if ( sum % 3 == 0 ) { ans = make_pair ( 0 , i - 1 ) ; found = 1 ; } for ( int j = i ; j < arr . size ( ) ; j ++ ) { if ( found == 1 ) break ; sum = sum + arr [ j ] - arr [ j - k ] ; if ( sum % 3 == 0 ) { ans = make_pair ( j - k + 1 , j ) ; found = 1 ; } } if ( found == 0 ) ans = make_pair ( -1 , 0 ) ; if ( ans . first == -1 ) { cout << -1 ; } else { for ( i = ans . first ; i <= ans . second ; i ++ ) { cout << arr [ i ] << " ▁ " ; } } } int main ( ) { vector < int > arr = { 84 , 23 , 45 , 12 , 56 , 82 } ; int K = 3 ; findSubArray ( arr , K ) ; return 0 ; }