Advertisement
STANAANDREY

Subarr given sum

Sep 17th, 2019
269
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.64 KB | None | 0 0
  1. #include "bits/stdc++.h"
  2. using namespace std;
  3.  
  4. inline void SubArrSum(int v[], int n, int sum)
  5. {
  6.     int currsum = v[0], j = 0;
  7.     bool existsum = false;
  8.     for (int i = 1; i <= n; i++)
  9.     {
  10.         while (currsum > sum && j < i)
  11.         {
  12.             currsum -= v[j];
  13.             j++;
  14.         }
  15.         if (currsum == sum)
  16.         {
  17.             existsum = true;
  18.             cout << j << ' ' << i - 1 << endl;
  19.         }
  20.         currsum += v[i];
  21.     }
  22.     if (!existsum)
  23.         cout << "Sum not found";
  24. }
  25.  
  26. int main()
  27. {
  28.     int v[] = {15, 2, 4, 8, 9, 5, 10, 23}, n = 8, sum = 23;
  29.     SubArrSum(v, n, sum);
  30.     return 0;
  31. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement