Check if a subarray of size K exists whose elements form a number divisible by 3 | Java 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
import java . util . * ; import java . awt . Point ; class GFG { public static void findSubArray ( Vector < Integer > arr , int k ) { Point ans = new Point ( 0 , 0 ) ; int i , sum = 0 ; for ( i = 0 ; i < k ; i ++ ) { sum += arr . get ( i ) ; } int found = 0 ; if ( sum % 3 == 0 ) { ans = new Point ( 0 , i - 1 ) ; found = 1 ; } for ( int j = i ; j < arr . size ( ) ; j ++ ) { if ( found == 1 ) break ; sum = sum + arr . get ( j ) - arr . get ( 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 ) { System . out . print ( - 1 ) ; } else { for ( i = ans . x ; i <= ans . y ; i ++ ) { System . out . print ( arr . get ( i ) + " ▁ " ) ; } } } public static void main ( String [ ] args ) { Vector < Integer > arr = new Vector < Integer > ( ) ; arr . add ( 84 ) ; arr . add ( 23 ) ; arr . add ( 45 ) ; arr . add ( 12 ) ; arr . add ( 56 ) ; arr . add ( 82 ) ; int K = 3 ; findSubArray ( arr , K ) ; } }