Longest Subarray consisting of unique elements from an Array | C # program to implement the above approach ; Function to find largest subarray with no duplicates ; Stores index of array elements ; Update j based on previous occurrence of a [ i ] ; Update ans to store maximum length of subarray ; Store the index of current occurrence of a [ i ] ; Return readonly ans ; Driver Code
using System ; using System . Collections . Generic ; class GFG { static int largest_subarray ( int [ ] a , int n ) { Dictionary < int , int > index = new Dictionary < int , int > ( ) ; int ans = 0 ; for ( int i = 0 , j = 0 ; i < n ; i ++ ) { j = Math . Max ( index . ContainsKey ( a [ i ] ) ? index [ a [ i ] ] : 0 , j ) ; ans = Math . Max ( ans , i - j + 1 ) ; if ( index . ContainsKey ( a [ i ] ) ) index [ a [ i ] ] = i + 1 ; else index . Add ( a [ i ] , i + 1 ) ; } return ans ; } public static void Main ( String [ ] args ) { int [ ] arr = { 1 , 2 , 3 , 4 , 5 , 1 , 2 , 3 } ; int n = arr . Length ; Console . Write ( largest_subarray ( arr , n ) ) ; } }