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(sum==k){
  13. if(maxi<i+1){
  14. maxi=i+1;
  15. count=1;
  16. }
  17. else if(maxi==i+1){
  18. count++;
  19. }
  20. }
  21. if(m.find(x)!=m.end()){
  22. int dist=m[x]+1;
  23. int actual=i-dist+1;
  24. if(actual>maxi){
  25. maxi=actual;
  26. count=1;
  27. }
  28. else if(actual==maxi){
  29. count++;
  30. }
  31.  
  32. }
  33. if(m.find(sum)==m.end()){
  34. m[sum]=i;
  35. }
  36.  
  37. }
  38. return count;
  39. }
  40.  
  41. int main() {
  42. // your code goes here
  43. int n;
  44. cin>>n;
  45. int k;
  46. cin>>k;
  47. int A[n];
  48. for(int i=0;i<n;i++){
  49. cin>>A[i];
  50. }
  51. cout<<"The count of subarrays with longest length whose sum==k is:"<<count(A,n,k);
  52. return 0;
  53. }
Success #stdin #stdout 0.01s 5312KB
stdin
8 15
10 5 2 7 1 9 8 7
stdout
The count of subarrays with longest length whose sum==k is:1