// Sum of Sub-Array
#include<iostream>
#include<vector>
using namespace std;
void firstSubArray(vector<int> arr, int size, int sum)
{
int newSum = 0;
int beginPos=0;
for(int i = 0; i<size; i++)
{
newSum += arr.at(i);
if(newSum > sum)
{
newSum = newSum - arr.front();
arr.erase(arr.begin());
beginPos++;
}
if(newSum == sum) {
cout << beginPos + 1 << " " << i + 1;
return;
}
}
cout<<"-1";
}
int main()
{
int testCases;
cin>>testCases;
int size, sum;
int temp;
for(int j = 0; j<testCases; j++) {
cin>>size>>sum;
vector<int>arr;
for (int i = 0; i < size; i++) {
cin >> temp;
arr.push_back(temp);
}
firstSubArray(arr, size, sum);
cout<<endl;
}
return 0;
}
Question: Given an unsorted array A of size N of non-negative integers, find a continuous sub-array which adds to a given number S. My code gives correct ans for the given test cases but shows a run time error on submitting.
Error: Runtime Error: Runtime ErrorAbort signal from abort(3) (SIGABRT)
Link: Question Link
You are trying to access a position in the vector that does not exist. The executor on the server detects this condition and aborts. As a first step, change the arr
to vector < int > const &arr
.