Untitled

mail@pastecode.io avatar
unknown
plain_text
24 days ago
480 B
1
Indexable
Never
class Solution {
public:
    int subarraySum(vector<int>& arr, int k) {
        unordered_map<int,int>mp;
        int n=arr.size();
        vector<int>pre(n,0);
        pre[0]=arr[0];
        int res=0;

        for(int i=1;i<arr.size();i++){
            pre[i]=arr[i]+pre[i-1];
        }

        for(int i=0;i<n;i++){
            if(pre[i]==k) res++;
            if(mp.find(pre[i]-k)!=mp.end()) res+=mp[pre[i]-k];
            mp[pre[i]]++;
        }
        return res;
    }
};
Leave a Comment