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 code ; Given array and K ; Function call
using System ; using System . Collections . Generic ; class GFG { class Point { public int x , y ; public Point ( int first , int second ) { this . x = first ; this . y = second ; } } public static void findSubArray ( List < int > arr , int k ) { Point ans = new Point ( 0 , 0 ) ; int i , sum = 0 ; for ( i = 0 ; i < k ; i ++ ) { sum += arr [ i ] ; } int found = 0 ; if ( sum % 3 == 0 ) { ans = new Point ( 0 , i - 1 ) ; found = 1 ; } for ( int j = i ; j < arr . Count ; j ++ ) { if ( found == 1 ) break ; sum = sum + arr [ j ] - arr [ j - k ] ; if ( sum % 3 == 0 ) { ans = new Point ( j - k + 1 , j ) ; found = 1 ; } } if ( found == 0 ) ans = new Point ( - 1 , 0 ) ; if ( ans . x == - 1 ) { Console . Write ( - 1 ) ; } else { for ( i = ans . x ; i <= ans . y ; i ++ ) { Console . Write ( arr [ i ] + " ▁ " ) ; } } } public static void Main ( String [ ] args ) { List < int > arr = new List < int > ( ) ; arr . Add ( 84 ) ; arr . Add ( 23 ) ; arr . Add ( 45 ) ; arr . Add ( 12 ) ; arr . Add ( 56 ) ; arr . Add ( 82 ) ; int K = 3 ; findSubArray ( arr , K ) ; } }