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. // m[0]=1;
  6. int count=0;
  7. int sum=0;
  8. int maxi=-100;
  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>maxi){
  16. maxi=actual;
  17. count=1;
  18. }
  19. else if(actual==maxi){
  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 longest length whose sum==k is:"<<count(A,n,k);
  43. return 0;
  44. }
Success #stdin #stdout 0.01s 5284KB
stdin
8 15
10 
5 
2 
7 
1 
9 
8 
7
stdout
The count of subarrays with longest length whose sum==k is:1