Length of longest subarray whose sum is not divisible by integer K | Function to find the longest subarray with sum is not divisible by k ; left is the index of the leftmost element that is not divisible by k ; right is the index of the rightmost element that is not divisible by k ; sum of the array ; Find the element that is not multiple of k ; left = - 1 means we are finding the leftmost element that is not divisible by k ; Updating the rightmost element ; Update the sum of the array up to the index i ; Check if the sum of the array is not divisible by k , then return the size of array ; All elements of array are divisible by k , then no such subarray possible so return - 1 ; Length of prefix elements that can be removed ; Length of suffix elements that can be removed ; Return the length of subarray after removing the elements which have lesser number of elements ; Driver Code
function MaxSubarrayLength ( arr , n , k ) { let left = - 1 ; let right = 0 ; let sum = 0 ; for ( let i = 0 ; i < n ; i ++ ) { if ( ( arr [ i ] % k ) != 0 ) { if ( left == - 1 ) { left = i ; } right = i ; } sum += arr [ i ] ; } if ( ( sum % k ) != 0 ) { return n ; } else if ( left == - 1 ) { return - 1 ; } else { let prefix_length = left + 1 ; let suffix_length = n - right ; return n - Math . min ( prefix_length , suffix_length ) ; } } let arr = [ 6 , 3 , 12 , 15 ] ; let n = arr . length ; let K = 3 ; document . write ( MaxSubarrayLength ( arr , n , K ) ) ;