Approach

This is quite easy to see that is a two pointer type of problem.

One difficult part is that for the boundary condition, such as one elemenet only may need some carefull handling (I get WA on that).

Also, the sum should remove duplicates so we need to store the count for each variable with a hashmap. Add when there is no this element in the range yet, and remove if this is the last one in the range! (also get 1 WA on this…)

Code

class Solution {
public:
    int minLength(vector<int>& nums, int k) {
        int n = nums.size();
        int l = 0;
        int sum = 0; // will over range? -> no
        unordered_map<int,int> cnt;
        int minLen = INT_MAX;
        for(int r = 0 ; r < n ; ++r) {
            // cout << "r=" << r << endl;
            if(!cnt.count(nums[r])) {
                sum += nums[r];
            }
            ++cnt[nums[r]];
            while(sum >= k && l <= r) {
                // cout << "   r=" << r << " l=" << l << endl;
                minLen = min(r-l+1, minLen);
                if(l == n) return minLen;
                --cnt[nums[l]];
                if(cnt[nums[l]] == 0) {
                    cnt.erase(nums[l]);
                    sum -= nums[l];
                }
                ++l;
            }
        }
        return minLen == INT_MAX ? -1 : minLen;
    }
};