fork download
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. int main() {
  5. int arr[]= {10,5,2,7,1,9};
  6. int n=sizeof(arr)/sizeof(arr[0]);
  7. int k=15;
  8. int currSum=0;
  9. int maxLength=INT_MIN;
  10. map<int, int> pSum;
  11. pSum[0] = -1; //indicates that pSum=0 exists at index i-1 bcoz we need pSum(i-1)
  12. //and what if i is 0 i.e. valid subarray starts from index 0 itself
  13. for(int j=0;j<n;j++){
  14. currSum+=arr[j];
  15. int toFind=currSum-k;
  16. if(pSum.find(toFind)!=pSum.end()){
  17. int index=pSum[toFind];
  18. maxLength=max(maxLength, j-index);
  19. }
  20. if(pSum.find(currSum)==pSum.end()){
  21. pSum[currSum]=j;
  22. }
  23. }
  24. cout<<maxLength;
  25. return 0;
  26. }
  27.  
Success #stdin #stdout 0s 5320KB
stdin
Standard input is empty
stdout
4