fork download
  1. #include<bits/stdc++.h>
  2. #include <unordered_map>
  3. using namespace std;
  4.  
  5. int main() {
  6. // your code goes here
  7. int arr[]={1, 2, 3, 4, 5, -1, 6};
  8. int k=9;
  9. int n=sizeof(arr)/sizeof(arr[0]);
  10. int sum=0;
  11. int maxi=0;
  12.  
  13. unordered_map<int,int>m;
  14. m[0]=0;
  15. for(int i=0;i<n;i++){
  16. sum+=arr[i];
  17. int un=sum-k;
  18. if(m.find(un)!=m.end()){
  19. int dist=i-m[un]+1;
  20. if(dist>maxi){
  21. maxi=dist;
  22. }
  23.  
  24. }
  25. if(m.find(sum)==m.end()){
  26. m[sum]=i;
  27. }
  28. }
  29. cout<<maxi;
  30. return 0;
  31. }
Success #stdin #stdout 0.01s 5312KB
stdin
Standard input is empty
stdout
4