fork download
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3. int count(int A[],int num,int k){
  4. unordered_map<int,int>m;
  5. int count=0;
  6. int sum=0;
  7. int mini=1e9;
  8. m[0]=-1; //beacuse a subarray sum may be equal to k so in map we does not have sum store with 0(zero value) so we need to store it so store it -1 (because when we calculte the distance we get correct distance using -1 value) )
  9. for(int i=0;i<num;i++){
  10. sum+=A[i];
  11. int x=sum-k;
  12. if(m.find(x)!=m.end()){
  13. int dist=m[x]+1;
  14. int actual=i-dist+1;
  15. if(actual<mini){
  16. mini=actual;
  17. count=1;
  18. }
  19. else if(actual==mini){
  20. count++;
  21. }
  22.  
  23. }
  24. if(m.find(sum)==m.end()){
  25. m[sum]=i;
  26. }
  27.  
  28. }
  29. return count;
  30. }
  31.  
  32. int main() {
  33. // your code goes here
  34. int n;
  35. cin>>n;
  36. int k;
  37. cin>>k;
  38. int A[n];
  39. for(int i=0;i<n;i++){
  40. cin>>A[i];
  41. }
  42. cout<<"The count of subarrays with smallest length whose sum==k is:"<<count(A,n,k);
  43. return 0;
  44. }
Success #stdin #stdout 0s 5320KB
stdin
8 15
10 5 2 7 1 9 8 7
stdout
The count of subarrays with smallest length whose sum==k is:2