Longest subarray such that the difference of max and min is at | Python 3 code to find longest subarray with difference between max and min as at - most 1. ; longest constant range length ; first number ; If we see same number ; If we see different number , but same as previous . ; If number is neither same as previous nor as current . ; Driver Code
def longestSubarray ( input , length ) : NEW_LINE INDENT prev = - 1 NEW_LINE prevCount = 0 NEW_LINE currentCount = 1 NEW_LINE longest = 1 NEW_LINE current = input [ 0 ] NEW_LINE for i in range ( 1 , length ) : NEW_LINE INDENT next = input [ i ] NEW_LINE if next == current : NEW_LINE INDENT currentCount += 1 NEW_LINE DEDENT elif next == prev : NEW_LINE INDENT prevCount += currentCount NEW_LINE prev = current NEW_LINE current = next NEW_LINE currentCount = 1 NEW_LINE DEDENT else : NEW_LINE INDENT longest = max ( longest , currentCount + prevCount ) NEW_LINE prev = current NEW_LINE prevCount = currentCount NEW_LINE current = next NEW_LINE currentCount = 1 NEW_LINE DEDENT DEDENT return max ( longest , currentCount + prevCount ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT input = [ 5 , 5 , 6 , 7 , 6 ] NEW_LINE n = len ( input ) NEW_LINE print ( longestSubarray ( input , n ) ) NEW_LINE DEDENT