fork download
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. int main()
  5. {
  6. //AtMost K -> we are doing that we are finding the longest subarray for the current window
  7.  
  8. int n=5;
  9. int a[] = {1,11,2,3,15};
  10. int k=10; //sum<=k
  11.  
  12. int cnt = 0;
  13. int sum = 0;
  14.  
  15. int i=0 , j=0;
  16.  
  17. while(j<n)
  18. {
  19. // do calculation
  20. sum = sum + a[j]; // running sum find out kela
  21.  
  22. if(sum<=k) // if the sum is less than equal to k
  23. {
  24. // finding ans <- from calculation
  25. cnt = cnt + (j-i+1); // keep counting the subarray
  26.  
  27. j++; // keep on moving 'j' pointer when sum <= k
  28. }
  29. else if(sum>k)
  30. {
  31. while(i<=j && sum>k) // This while loop will run until the sum>k
  32. {
  33. sum = sum - a[i]; // we will start removing the ' i ' index element from the window
  34.  
  35. i++; // we will increment the ' i ' pointer
  36. }
  37. //after coming from this while loop there can only two possibilities
  38. //Edge case -> why this edge case??
  39. // 1. possibility -> current sum <=k
  40. //2. possibility -> sum==0 or the sum!=0
  41. if(sum<=k && sum!=0) // so when sum<=k and sum!=0 we have go our subarrays
  42. {
  43. cnt = cnt + (j-i+1); // again keep on counting the subarrays
  44.  
  45. j++;
  46. }
  47. else if(sum==0)
  48. {
  49. j++;
  50. }
  51. }
  52. }
  53. cout<<cnt<<" ";
  54. }
  55.  
Success #stdin #stdout 0s 5312KB
stdin
Standard input is empty
stdout
4