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 ; 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
def MaxSubarrayLength ( arr , n , k ) : NEW_LINE INDENT left = - 1 NEW_LINE sum = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( ( arr [ i ] % k ) != 0 ) : NEW_LINE INDENT if ( left == - 1 ) : NEW_LINE INDENT left = i NEW_LINE DEDENT right = i NEW_LINE DEDENT sum += arr [ i ] NEW_LINE DEDENT if ( ( sum % k ) != 0 ) : NEW_LINE INDENT return n NEW_LINE DEDENT elif ( left == - 1 ) : NEW_LINE INDENT return - 1 NEW_LINE DEDENT else : NEW_LINE INDENT prefix_length = left + 1 NEW_LINE suffix_length = n - right NEW_LINE return n - min ( prefix_length , suffix_length ) NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 6 , 3 , 12 , 15 ] NEW_LINE n = len ( arr ) NEW_LINE K = 3 NEW_LINE print ( MaxSubarrayLength ( arr , n , K ) ) NEW_LINE DEDENT