Friday, 10 August 2018

Divide array into two sub-arrays such that their averages are equal

public class SplitArrayInTwoAverageEqual {

    public static void main(String[] args) {
        int[] arr = {1,5,7,2,0};
        int n = arr.length;
        int sum = 0;
        for(int i=0;i<n;i++) {
            sum+=arr[i];
        }
      
        int lsum = 0;
      
        for(int i=0;i<n-1;i++) {
            lsum+=arr[i];
            int rsum = sum-lsum;
            if(lsum*(n-i-1)==rsum*(i+1)) {
                System.out.println("first is: 0 to "+i+" and other is: "+(i+1) +" to "+ (n-1));
            }
        }
      
    }

}

output: first is: 0 to 1 and other is: 2 to 4

No comments:

Post a Comment

links for Data Structure

  1) 𝐁𝐞𝐜𝐨𝐦𝐞 𝐌𝐚𝐬𝐭𝐞𝐫 𝐢𝐧 𝐋𝐢𝐧𝐤𝐞𝐝 𝐋𝐢𝐬𝐭:  https://lnkd.in/gXQux4zj 2) 𝐀𝐥𝐥 𝐭𝐲𝐩𝐞𝐬 𝐨𝐟 𝐓𝐫𝐞𝐞 𝐓𝐫𝐚𝐯𝐞𝐫𝐬𝐚𝐥𝐬...