Longest subarray such that the difference of max and min is at | C ++ 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
#include <bits/stdc++.h> NEW_LINE using namespace std ; int longestSubarray ( int input [ ] , int length ) { int prev = -1 ; int current , next ; int prevCount = 0 , currentCount = 1 ; int longest = 1 ; current = input [ 0 ] ; for ( int 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 ) ; } int main ( ) { int input [ ] = { 5 , 5 , 6 , 7 , 6 } ; int n = sizeof ( input ) / sizeof ( int ) ; cout << longestSubarray ( input , n ) ; return 0 ; }