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 final ans ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int largest_subarray ( int a [ ] , int n ) { unordered_map < int , int > index ; int ans = 0 ; for ( int i = 0 , j = 0 ; i < n ; i ++ ) { j = max ( index [ a [ i ] ] , j ) ; ans = max ( ans , i - j + 1 ) ; index [ a [ i ] ] = i + 1 ; } return ans ; } int32_t main ( ) { int arr [ ] = { 1 , 2 , 3 , 4 , 5 , 1 , 2 , 3 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << largest_subarray ( arr , n ) ; }