fork download
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. int main() {
  5. vector<int> arr={5,1,1,0,2}; //To find total number of subarrays- n*(n+1)/2
  6. int n=arr.size();
  7. int count=0, sum=0;
  8. int k=4;
  9. /* brute force approach may be have O(N2)
  10. we can perform operation (like sum) on each subarray using O(n2) but we cannot print the all
  11. subarray using just O(n2)
  12. */
  13. for(int i=0;i<5;i++){
  14. int sum=0;
  15. for(int j=i;j<5;j++){
  16. sum+=arr[j];
  17. if(sum==j-i+1){
  18. count++;
  19. }
  20.  
  21. }
  22.  
  23. }
  24. cout<<count;
  25. // unordered_map<int ,int> ok;
  26. // int count=0 ,sum=0;
  27. // for(int i=0;i<arr.size();i++){
  28. // sum+=arr[i];
  29. // if(ok.find(sum-i)!=ok.end()){
  30. // count+=ok[sum-i];
  31. // }
  32. // ok[sum-i]++;
  33. // }
  34. // cout<<count;
  35. return 0;
  36. }
Success #stdin #stdout 0s 5304KB
stdin
Standard input is empty
stdout
6