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
def CountLongestSubarrays ( arr , n , k ) : NEW_LINE INDENT s = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT s += arr [ i ] NEW_LINE DEDENT if ( s % k ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT else : NEW_LINE INDENT ini = 0 NEW_LINE while ( ini < n and arr [ ini ] % k == 0 ) : NEW_LINE INDENT ini += 1 NEW_LINE DEDENT final = n - 1 NEW_LINE while ( final >= 0 and arr [ final ] % k == 0 ) : NEW_LINE INDENT final -= 1 NEW_LINE DEDENT sum , count = 0 , 0 NEW_LINE if ( ini == n ) : NEW_LINE INDENT return - 1 NEW_LINE DEDENT else : NEW_LINE INDENT length = max ( n - 1 - ini , final ) NEW_LINE DEDENT for i in range ( length ) : NEW_LINE INDENT sum += arr [ i ] NEW_LINE DEDENT if ( sum % k != 0 ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT for i in range ( length , n ) : NEW_LINE INDENT sum = sum + arr [ i ] NEW_LINE sum = sum + arr [ i - length ] NEW_LINE if ( sum % k != 0 ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT DEDENT return count NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 3 , 2 , 2 , 2 , 3 ] NEW_LINE n = len ( arr ) NEW_LINE k = 3 NEW_LINE print ( CountLongestSubarrays ( arr , n , k ) ) NEW_LINE DEDENT