Count of longest possible subarrays with sum not divisible by K | Function to find the count of longest subarrays with sum not divisible by K ; Sum of all elements in an array ; If overall sum is not divisible then return 1 , as only one subarray of size n is possible ; Index of the first number not divisible by K ; Index of the last number not divisible by K ; Subarray doesn 't exist ; Sum of the window ; Calculate the sum of rest of the windows of size len ; Driver Code
function CountLongestSubarrays ( arr , n , k ) { let i , s = 0 ; for ( i = 0 ; i < n ; ++ i ) { s += arr [ i ] ; } if ( ( s % k ) != 0 ) { return 1 ; } else { let ini = 0 ; while ( ini < n && arr [ ini ] % k == 0 ) { ++ ini ; } let fin = n - 1 ; while ( fin >= 0 && arr [ fin ] % k == 0 ) { -- fin ; } let len , sum = 0 , count = 0 ; if ( ini == n ) { return - 1 ; } else { len = Math . max ( n - 1 - ini , fin ) ; } for ( i = 0 ; i < len ; i ++ ) { sum += arr [ i ] ; } if ( sum % k != 0 ) { count ++ ; } for ( i = len ; i < n ; i ++ ) { sum = sum + arr [ i ] ; sum = sum - arr [ i - len ] ; if ( sum % k != 0 ) { count ++ ; } } return count ; } } let arr = [ 3 , 2 , 2 , 2 , 3 ] ; let n = arr . length ; let k = 3 ; document . write ( CountLongestSubarrays ( arr , n , k ) ) ;