Skip to content

Instantly share code, notes, and snippets.

@mk6619
Last active December 1, 2019 03:39
Show Gist options
  • Select an option

  • Save mk6619/46f4277ff1b0d8befb10fbfd947044aa to your computer and use it in GitHub Desktop.

Select an option

Save mk6619/46f4277ff1b0d8befb10fbfd947044aa to your computer and use it in GitHub Desktop.
#include <iostream>
using namespace std;
int main() {
int arrayLength,sum,testCases;
cin>>testCases;
for(int i = 0; i < testCases; i++) {
cin>>arrayLength>>sum;
int arr[arrayLength];
for(int j = 0 ; j < arrayLength; j++) {
cin>>arr[j];
}
int left = 0,right = 0;
int flag = 0;
int sumSubArray = 0;
while(flag == 0 && left < arrayLength && right <= arrayLength) {
// if requiredSum is greater than sum of all elements of array
if(left == 0 && right == arrayLength) {
break;
}
if(sumSubArray < sum) {
sumSubArray = sumSubArray + arr[right];
right++;
}
if(sumSubArray > sum) {
sumSubArray = sumSubArray - arr[left];
left++;
}
if(sumSubArray == sum) {
flag = 1;
break;
}
}
if (flag == 0) {
cout<<-1<<"\n";
} else {
cout<<left+1<<" "<<right<<"\n";
}
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment