Code For Alls..!

get the code!!

Saturday, 22 July 2017

Sherlock and Array

Watson gives Sherlock an array of length . Then he asks him to determine if there exists an element in the array such that the sum of the elements on its left is equal to the sum of the elements on its right. If there are no elements to the left/right, then the sum is considered to be zero.
Formally, find an , such that, .
Input Format
The first line contains , the number of test cases. For each test case, the first line contains , the number of elements in the array . The second line for each test case contains space-separated integers, denoting the array .
Constraints



Output Format
For each test case print YES if there exists an element in the array, such that the sum of the elements on its left is equal to the sum of the elements on its right; otherwise print NO.
Sample Input 0
2
3
1 2 3
4
1 2 3 3
Sample Output 0
NO
YES
Explanation 0
For the first test case, no such index exists.
For the second test case, , therefore index satisfies the given conditions.

Java Code:
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;

public class Solution {

    static String solve(int[] a){
       if(a.length==1)
           return "YES" ;
        if(a.length==2)
            return "NO" ;
        int r=0,l=0;
        for(int i=0;i<a.length;i++)
           r+=a[i];
       r=r-a[0];
        for(int i=1;i<a.length;i++)
        {
            l=l+a[i-1];
            r=r-a[i];
            if(l==r)
            return "YES" ;
        }
    return "NO" ;
    }

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int T = in.nextInt();
        for(int a0 = 0; a0 < T; a0++){
            int n = in.nextInt();
            int[] a = new int[n];
            for(int a_i=0; a_i < n; a_i++){
                a[a_i] = in.nextInt();
            }
            String result = solve(a);
            System.out.println(result);
        }
    }
}

No comments:

Post a Comment