DEV Community

Guhan M
Guhan M

Posted on

Distinct Values Subarrays II | CSES - Algoritmit ongelmanratkaisussa


#include <iostream>
#include <vector>
#include <unordered_map>

typedef long long ll;

using namespace std;

int main() {
    ios_base::sync_with_stdio(false);
    cin.tie(nullptr);

    int n, k;
    cin >> n >> k;

    vector<ll> arr(n);
    for (int i = 0; i < n; i++) {
        cin >> arr[i];
    }

    unordered_map<ll, int> freq;
    int left = 0, right = 0;
    ll count = 0;

    while (right < n) {
        int curr = arr[right];
        freq[curr]++;
        int distinct = freq.size();
        while (distinct > k) {
            freq[arr[left]]--;
            if (freq[arr[left]] == 0) {
                distinct--;
                freq.erase(arr[left]);
            }
            left++;
        }
        count += right - left + 1;
        right++;
    }
    cout << count << endl;
    return 0;

}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)