Monday, 17 August 2015

Modify Sequence

Standard
Suppose we have a sequence of non-negative integers, Namely a_1, a_2, ... ,a_n. At each time we can choose one term a_i with 0 < i < n and we subtract 1 from both a_i and a_i+1. We wonder whether we can get a sequence of all zeros after several operations.
Input
The first line of test case is a number N. (0 < N <= 10000) The next line is N non-negative integers, 0 <= a_i <= 109
Output
If it can be modified into all zeros with several operations output “YES” in a single line, otherwise output “NO” instead.

Sample Input
2
1 2
Sample Output
NO
Explanation
It is clear that [1 2] can be reduced to [0 1] but no further to convert all integers to 0. Hence, the output is NO.
Consider another input for more clarification:
2 2 2
Output is YES as [2 2] can be reduced to [1 1] and then to [0 0] in just two steps.

Time Limit: 3 sec(s) for all input files combined.
Memory Limit: 256 MB
Source Limit: 1024 KB 
 
Code: 
 
import java.io.*;
public class ModifySequence {
    public static void main(String args[]) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        int n,i,a[];
        long odd=0,even=0;
        n = Integer.parseInt(br.readLine());
        String s[] = br.readLine().split(" ");
        a = new int[n];
        for(i=0;i<n;i++)
        {
            a[i] = Integer.parseInt(s[i]);
            if(i%2 == 0)
            even = even + a[i];
            else
            odd = odd + a[i];
        }
        if(even == odd)
        System.out.println("YES");
        else
        System.out.println("NO");
    }

0 comments:

Post a Comment