find subarray sum using c 2b 2b

Solutions on MaxInterview for find subarray sum using c 2b 2b by the best coders in the world

showing results for - "find subarray sum using c 2b 2b"
Yannic
03 Mar 2016
1#include <iostream>
2using namespace std;
3int main()
4{
5    int arrayLen, totalSum;
6    int arr[20];
7
8    //input
9    cin >> arrayLen >> totalSum;
10    for (int i = 0; i < arrayLen; i++)
11    {
12        cin >> arr[i];
13    }
14    
15    //algo
16    // j => Loop iterator
17    int i = 0, j = 0, start = -1, end = -1, sum = 0;
18
19    while (j < arrayLen && sum + arr[j] <= totalSum) 
20    {
21        sum += arr[j];
22        j++;
23    } // after this loop sum is either greater than or equal to totalSum
24
25    // If sum is equal
26    if (sum == totalSum)
27    {
28        cout << i + 1 << " " << j << endl;
29        return 0;
30    }
31    
32    while (j < arrayLen)
33    {
34        sum += arr[j];
35        
36        while (sum > totalSum)
37        {
38            sum -= arr[i];
39            i++;
40        }
41
42        if (sum == totalSum) //Store values
43        {
44            start = i + 1;
45            end = j + 1;
46            break;
47        }
48        j++;
49    }
50    cout << start <<" "<< end;
51
52    return 0;
53}