What is the problem with this code plzzzz help?


#1

public class Solution {
public int solve(ArrayList A) {
int n=A.size();

    for(int i=0;i<n;i++){
        int count=0;
        int lefteven=0,leftodd=0;
        for(int j=0;j<i;j++){
            if(j%2==0){
                lefteven+=A.get(j);
            }else{
                leftodd+=A.get(j);
            }
            
        }
        int rightodd=0,righteven=0;
        for(int k=i+1;k<n;k++){
            if(k%2==0){
                rightodd+=A.get(k);
            }else{
                righteven+=A.get(k);
            }
        
        }
        if((lefteven+rightodd)==(leftodd+righteven)){
            count++;
        }
        return count;
    }
    return -1;
    
}

}


#2

The logic seems to be correct. But it has a higher time complexity(O(n^2)). This is because you are calculating the left and right (even and odd) values for each pass of the outer loop. Instead calculate the evensum and oddsum once and then keep on updating the lefteven, rightodd, leftodd and lefteven. You can do this as follows:
Initially lefteven and leftodd are 0 rightodd = even and righteven = odd
When you pass through the outer loop update the above variables as applicable.
Basically you will need to add to the left terms and subtract from the right terms using some conditions.