Divide and Rule: You are given with an array size and elements, need to remove any one of the elements, such that remaining elements has to divided into two halves and their sum should be equal, if both halves sum are equal need to return 1 else return -1.

Divide and Rule: You are given with an array size and elements, need to remove any one of the elements, such that remaining elements has to divided into two halves and their sum should be equal, if both halves sum are equal need to return 1 else return -1.


import java.util.*;
public class TechWeekChallenge4 {
public static int divideAndRule(int[] input1)
{
int output=0;
if(input1.length%2==0){
output=-1; //if array size is even we can't divide into equal halves.
}
else{
int length=input1.length;
int i=0,j=1,secondMax=length-2,secondMin=secondMax-1,divide=(input1.length-1)/2;
int firstHalf=0,secondHalf=0;
Arrays.sort(input1); //sorting the array
while(i<=divide && j<=divide){
firstHalf+=input1[i];
secondHalf+=input1[j];
i+=2;
j+=2;
}
firstHalf+=input1[secondMax];
secondHalf+=input1[secondMin];
if(firstHalf==secondHalf){
output=1;
}else{
output=-1;
}
}
return output;
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int output = 0;
int ip1_size = 0;
ip1_size = Integer.parseInt(in.nextLine().trim());
int[] ip1 = new int[ip1_size];
int ip1_item;
for(int ip1_i = 0; ip1_i < ip1_size; ip1_i++) {
ip1_item = Integer.parseInt(in.nextLine().trim());
ip1[ip1_i] = ip1_item;
}
output = divideAndRule(ip1);
System.out.println(String.valueOf(output));
in.close();
}
}

Input: 7                         //Array size
1   -----------------
2                         |
3                         |
4                         | -------Array Elements
5                         |
6                         |
7-------------------


Output:
-1

Comments

Popular posts from this blog

Reasoning-Number Series

Profit and Loss

Reasoning-Letter Series