I found a programming challenge online and was wondering if there is a more efficient solution to this.
The problem: You are given a list of n numbers along with a number X which refers to the maximum number of different numbers that can be contained in a contiguous sub-array. We need to count all such contiguous sub-arrays which satisfy the condition imposed by X.
Input On the first row are two numbers n and x; the amount of numbers and the maximum number of unique numbers in the subarray.
Example:
5 2
1 2 3 1 1
ans = 10
explanation: ([1],[2],[3],[1],[1],[1,2],[2,3],[3,1],[1,1],[3,1,1])
My approach Loop through all subarrays of the list using two loops and count the number of unique numbers in the concerned subarray (using a set). Surely, there must be a more efficient way to calculate this? Sorry if this question doesn't belong here, feel free to edit it.
EDIT: nellex's corrected code that sometimes gives the wrong answer
int main() {
int n, x;
cin >> n >> x;
vector<int> a;
for (int i = 1; i <= n; i++) {
int b;
cin >> b;
a.push_back(b);
}
int ans = 0, end = 1;
set<int> uniq;
map<int, int> freq;
for (int start = 0; start < n; start++) {
cout << start << " and end=" << end << endl;
while (uniq.size() <= x && end < n) {
if (uniq.size() == x && freq[a[end]] == 0) {
break;
}
uniq.insert(a[end]);
freq[a[end]]++;
end++;
}
cout << "added " << end << " - " << start << " to ans" << endl;
ans += end - start;
freq[a[start]]--;
if (freq[a[start]] == 0) {
uniq.erase(a[start]);
}
}
cout << ans;
}
EDIT: 1st test cases constraints:
1≤k≤n≤100
1≤xi≤10
The largest constraints:
1≤k≤n≤5⋅10^5
1≤xi≤10^9