Longest subarray such that the difference of max and min is at | PHP 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
< ? php function longestSubarray ( $ input , $ length ) { $ prev = -1 ; $ prevCount = 0 ; $ currentCount = 1 ; $ longest = 1 ; $ current = $ input [ 0 ] ; for ( $ i = 1 ; $ i < $ length ; $ i ++ ) { $ next = $ input [ $ i ] ; if ( $ next == $ current ) { $ currentCount ++ ; } else if ( $ next == $ prev ) { $ prevCount += $ currentCount ; $ prev = $ current ; $ current = $ next ; $ currentCount = 1 ; } else { $ longest = max ( $ longest , $ currentCount + $ prevCount ) ; $ prev = $ current ; $ prevCount = $ currentCount ; $ current = $ next ; $ currentCount = 1 ; } } return max ( $ longest , $ currentCount + $ prevCount ) ; } $ input = array ( 5 , 5 , 6 , 7 , 6 ) ; echo ( longestSubarray ( $ input , count ( $ input ) ) ) ; ? >