Equal Armies

Enough of humans fighting coronaviruses. How about coronaviruses fighting among themselves?

Corona-A and Corona-B are the commanders-in-chief of two coronavirus armies on a battlefield. The battlefield is in the form of a 3-D cartesian plane.

There are a total of N commandos where (Xi , Y, Z) denotes the position of the ith commando on the battlefield. Now, the border separating the armies is in the form of a 2-D plane. The equation of the plane is x + y + z = k [k being an integer].

Before starting the battle, Corona-A and Corona-B wonder if there exists a such that there are equal no. of commandos on either side of the border. Ignore the commandos on the border because they are of no use to the commanders-in-chief.

While Corona-A and Corona-B were so busy commanding armies throughout their lives that they did not focus on algorithms at all. Will you help them solve the problem and kill each other or will you leave them confused?

Example:

Input:  1
3
1 1 1
1 0 1
1 2 1
Output: YES

Approach

Java

import java.util.ArrayList;
import java.util.Collections;

public class EqualArmies {
    public static void main(String[] args) {

        int N = 3;
        ArrayList<IntegercommandosPosition = new ArrayList<>();
        int n = 0;
        int arr2D[][] = { { 111 }, { 101 }, { 121 } };
        while (n < N) {
            int sum = 0;
            for (int i = 0; i < arr2D[n].length; i++)
                sum += arr2D[n][i];

            commandosPosition.add(sum);
            n++;
        }

        Collections.sort(commandosPosition);
        if (N % 2 != 0) {
            int midNum = commandosPosition.get(N / 2);
            int firstIndexOfMidNum = commandosPosition.indexOf(midNum);
            int lastIndexOfMidNum = commandosPosition.lastIndexOf(midNum);
            if ((N / 2) - firstIndexOfMidNum == lastIndexOfMidNum - (N / 2))
                System.out.println("YES");
            else
                System.out.println("NO");
        } else {
            int midNum1 = commandosPosition.get((N - 1) / 2);
            int midNum2 = commandosPosition.get(N / 2);
            int diff = midNum2 - midNum1;
            if (diff < 0)
                diff *= -1;

            if (midNum1 == midNum2) {
                int firstIndexOfMidNum = commandosPosition.indexOf(midNum1);
                int lastIndexOfMidNum = commandosPosition.lastIndexOf(midNum2);
                if (((N - 1) / 2) - firstIndexOfMidNum == lastIndexOfMidNum - (N / 2))
                    System.out.println("YES");
                else
                    System.out.println("NO");
            } else if ((midNum1 != midNum2) && diff > 1)
                System.out.println("YES");
            else
                System.out.println("NO");
        }

    }
}


No comments:

Post a Comment