Given an array of elements, return the length of the longest subarray where all its elements are distinct.
For example, given the array [5, 1, 3, 5, 2, 3, 4, 1]
, return 5 as the longest subarray of distinct elements is [5, 2, 3, 4, 1]
.
Example:
Input: arr = {5, 1, 3, 5, 2, 3, 4, 1}
Output: 5
Approach
C++
#include <bits/stdc++.h>using namespace std;int longestSubarray(vector<int> &arr){int i = 0, j = 1;int max1 = 0, currLength = 1;max1 = max(max1, currLength);set<int> st;st.insert(arr[0]);while (i < arr.size() - 1 && j < arr.size()){if (st.find(arr[j]) == st.end()){currLength++;st.insert(arr[j++]);}else{st.erase(arr[i++]);currLength--;}}return max(currLength, max1);}int main(){vector<int> arr = {5, 1, 3, 5, 2, 3, 4, 1};cout << longestSubarray(arr);return 0;}
No comments:
Post a Comment