C++ Easy Solution with linear time and constant space. Must see!


#1

int Solution::solve(vector &a) {
long long int n = a.size();
long long int sum = 0;
long long int sumeven = 0;
long long int sumodd = 0;
for(int i = 0; i < n; i++)
{
sum = sum+a[i];
if(i%2 == 0)
{
sumeven = sumeven + a[i];
}
else
{
sumodd = sumodd + a[i];
}

}

long long int cou = 0;

long long int prefeven = 0;
long long int prefodd = 0;
long long int suffeven = 0;
long long int suffodd = 0;

for(int i = 0; i < n; i++)
{
    if(i%2 == 0)
    {
        prefeven = prefeven+a[i];
        suffeven = sumeven-prefeven+a[i];
    }
    else if(i%2 != 0)
    {
        prefodd = prefodd + a[i];
        suffodd = sumodd - prefodd+ a[i];
    }
    
    long long int tempsum = sum-a[i];
    
    if (tempsum % 2 == 0)
    {
        long long int temp = tempsum/2;
        if(i%2 == 0)
        {
            long long int y = prefodd+suffeven-a[i];
            if(y == temp)
            {
                cou++;
            }
        }
        else if(i % 2 != 0)
        {
            long long int z = prefeven+suffodd-a[i];
            if(z == temp)
            {
                cou++;
            }
        }
    }
    
}
return cou;

}