Time complexity

Please help in finding the time complexity of the given program.
I was writing the code to find a sub array whose sum is equal to the required sum

#include

#include

using namespace std;

int main()

{

vector<int> a;

int i,n,temp,currentsum,requiredsum,s,e;

char c;

cout<<"Enter the element of array and press enter to stop:-\n";

for(i=0;c!='\n';i++)

{

    scanf("%d%c",&temp,&c);

    a.push_back(temp);

}

n=a.size();

cout<<"Enter the required sum for subarrays:-\n";

cin>>requiredsum;

currentsum=a[0];

s=0;

e=0;

while(s<n && e<n)

{

    if(requiredsum>currentsum)

    {

        e++;

        currentsum=currentsum+a[e];

    }

    if(requiredsum<currentsum)

    {

        currentsum=currentsum-a[s];

        s++;

    }

    if(requiredsum==currentsum)

    {

        break;

    }

}

if(requiredsum!=currentsum)

{

    cout<<"The sum is not possible.\n";

    system("pause");

    return 0;

}

cout<<"The required sum is found between index "<<s<<" and "<<e<<"\n";

system("pause");

return 0;

}

it is O(n) .
As in worst case it will run till requiredsum==currentsum) which will be equal to n/2 each, giving time complexity as O(n);

1 Like