Longest subarray with difference exactly K between any two distinct values | C ++ implementation to find the longest subarray consisting of only two values with difference K ; Function to return the length of the longest sub - array ; Initialize set ; Store 1 st element of sub - array into set ; Check absolute difference between two elements ; If the new element is not present in the set ; If the set contains two elements ; Otherwise ; Update the maximum length ; Remove the set elements ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int longestSubarray ( int arr [ ] , int n , int k ) { int i , j , Max = 1 ; set < int > s ; for ( i = 0 ; i < n - 1 ; i ++ ) { s . insert ( arr [ i ] ) ; for ( j = i + 1 ; j < n ; j ++ ) { if ( abs ( arr [ i ] - arr [ j ] ) == 0 || abs ( arr [ i ] - arr [ j ] ) == k ) { if ( ! s . count ( arr [ j ] ) ) { if ( s . size ( ) == 2 ) break ; else s . insert ( arr [ j ] ) ; } } else break ; } if ( s . size ( ) == 2 ) { Max = max ( Max , j - i ) ; s . clear ( ) ; } else s . clear ( ) ; } return Max ; } int main ( ) { int arr [ ] = { 1 , 0 , 2 , 2 , 5 , 5 , 5 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int K = 1 ; int length = longestSubarray ( arr , N , K ) ; if ( length == 1 ) cout << -1 ; else cout << length ; return 0 ; }