[Microsoft Google interview question 100-[45] an integer array with a length of N, which is divided into M parts, so that the sum of each part is equal, and the maximum value of M is obtained.

Source: Internet
Author: User
45th questions

An integer array with the length of N. It is divided into M parts so that the sum of the parts is equal and the maximum value of M is obtained.

For example:

{3, 2, 4, 3, 6} can be divided:

{3, 2, 4, 3, 6} M = 1;

{3, 6} {2, 4, 3} m = 2

{3, 3} {2, 4} {6} M = 3 so the maximum m value is 3

Since the sum of parts is equal, the first thing that comes to mind is to sum up the array and then solve the number of groups.

Then define the variableI = length (array length), I> 0, I --To find the most satisfyingI

import java.util.ArrayList;import java.util.List;public class Algorithm45_0 {static int getMax(int a[]){int sum=0;List<Integer> myList=new ArrayList<Integer>();for(int aa:a){sum+=aa;myList.add(aa);}for(int i=a.length;i>0;i--){if(sum%i==0){if(ifExsits(myList,sum/i,sum/i)){return i;}}}return 1;}static boolean ifExsits(List<Integer> rootList,int num,int orgNum){if(rootList.size()==0&&num==orgNum){return true;}boolean flag=false;for(int i=0;i<rootList.size();i++){List<Integer> subList=new ArrayList<Integer>();for(int j=0;j<rootList.size();j++){if(j!=i){subList.add(rootList.get(j));}}if(rootList.get(i)==num){flag=flag||ifExsits(subList, orgNum, orgNum);}else if(rootList.get(i)<num){flag=flag||ifExsits(subList, num-rootList.get(i), orgNum);}}return flag;}public static void main(String[] args) {// TODO Auto-generated method stubint a[]={1,2,3,6,6};int b=getMax(a);System.err.println(b);}}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.