How to optimally divide an array into two subarrays so that sum of elements in both are same, otherwise give an error?

前端 未结 22 1012
一生所求
一生所求 2020-12-02 11:20

How to optimally divide an array into two subarrays so that sum of elements in both subarrays is same, otherwise give an error?

Example 1

Given the array

22条回答
  •  萌比男神i
    2020-12-02 12:05

    public class Problem1 {
    
    public static void main(String[] args) throws IOException{
        Scanner scanner=new Scanner(System.in);
        ArrayList array=new ArrayList();
        int cases;
        System.out.println("Enter the test cases");
        cases=scanner.nextInt();
    
        for(int i=0;i array){
        boolean flag=false;
        Collections.sort(array);
        System.out.println(array);
        int index=array.size();
    
        ArrayList sub1=new ArrayList();
        ArrayList sub2=new ArrayList();
    
        sub1.add(array.get(index-1));
        array.remove(index-1);
    
        index=array.size();
        sub2.add(array.get(index-1));
        array.remove(index-1);
    
        while(!array.isEmpty()){
    
        if(compareSum(sub1,sub2)){
            index=array.size();
            sub2.add(array.get(index-1));
            array.remove(index-1);
        }
        else{
            index=array.size();
            sub1.add(array.get(index-1));
            array.remove(index-1);
        }   
        }
    
        if(sumOfArray(sub1).equals(sumOfArray(sub2)))
            flag=true;
        else
            flag=false;
    
        return flag;
    }
    
    public static Integer sumOfArray(ArrayList array){
        Iterator it=array.iterator();
        Integer sum=0;
        while(it.hasNext()){
            sum +=it.next();
        }
    
        return sum;
    }
    
    public static boolean compareSum(ArrayList sub1,ArrayList sub2){
        boolean flag=false;
    
        int sum1=sumOfArray(sub1);
        int sum2=sumOfArray(sub2);
    
        if(sum1>sum2)
            flag=true;
        else
            flag=false;
    
        return flag;
    }
    
    }
    

    // The Greedy approach //

提交回复
热议问题