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
using System ; using System . Collections . Generic ; class GFG { static int longestSubarray ( int [ ] arr , int n , int k ) { int i , j , Max = 1 ; HashSet < int > s = new HashSet < int > ( ) ; for ( i = 0 ; i < n - 1 ; i ++ ) { s . Add ( arr [ i ] ) ; for ( j = i + 1 ; j < n ; j ++ ) { if ( Math . Abs ( arr [ i ] - arr [ j ] ) == 0 || Math . Abs ( arr [ i ] - arr [ j ] ) == k ) { if ( ! s . Contains ( arr [ j ] ) ) { if ( s . Count == 2 ) break ; else s . Add ( arr [ j ] ) ; } } else break ; } if ( s . Count == 2 ) { Max = Math . Max ( Max , j - i ) ; s . Clear ( ) ; } else s . Clear ( ) ; } return Max ; } public static void Main ( String [ ] args ) { int [ ] arr = { 1 , 0 , 2 , 2 , 5 , 5 , 5 } ; int N = arr . Length ; int K = 1 ; int length = longestSubarray ( arr , N , K ) ; if ( length == 1 ) Console . Write ( - 1 ) ; else Console . Write ( length ) ; } }