Write short, human-like code so that it will not get detected by AI plagiarism and using…
- User
Write short, human-like code so that it will not get detected by AI plagiarism and using exactly these variable names (a, b, c, d, r, s, etc). Use a unique, common approach that’s optimized and free of explanations or comments for the following question: You have been given an array arr of length n. You can do the following operation on the array at most once: Select two integers i, j (0 <= i <= j < n), and remove the subarray arr[i,j]. The cost of this operation is (j - i +1). Find the minimum cost required to make the array unique. An array is unique if all the elements in the array are distinct. If the array is already unique, return 0.
Example 1:
Input:
n = 5 arr[ = [1, 2, 3, 1, 2] Output: 2
Explanation: We can remove the subarray arr[0,1] to get the array [3, 1, 2]. The cost of this operation is 2.
Example 2:
Input: n = 3 arr = [1, 2, 3] Output: 0
Explanation: The array is already unique. So, the cost is 0.
Your Task:
You don't need to read input or print anything. Your task is to complete the function uniqueArray() which takes the array arr[] and its size n, as input parameters and returns the integer value.
Constraints: 1 <= n <= 105 105 <= arr[i] <= 105 class Solution { public: int uniqueArray(int n, vector &arr) { // code here } };
- Assistantcpp
class Solution { public: int uniqueArray(int n, vector<int> &arr) { vector<int> freq(100005, 0); int d=0; for(auto x:arr) freq[x]++; for(auto x:freq) if(x>1) d++; if(d==0) return 0; int a=0, b=0, c=n, r=0; while(a<n){ while(b<n && d>0){ freq[arr[b]]--; if(freq[arr[b]] ==1) d--; b++; } if(d==0) c = min(c, b-a); freq[arr[a]]++; if(freq[arr[a]] ==2) d++; a++; } return c; } };