一个整数数组,长度为n,将其分为m份,使各份的和相等,求m的最大值

2.一个整数数组,长度为n,将其分为m份,使各份的和相等,求m的最大值
  比如{3,2,4,3,6} 可以分成{3,2,4,3,6} m=1; 
  {3,6}{2,4,3} m=2
  {3,3}{2,4}{6} m=3 所以m的最大值为3

 

C# codes as below:

 

using System;

using System.Collections.Generic;

 

namespace ConsoleApp

{

    class RunClass

    {

        static void Main()

        {

            int[] array = { 3, 2, 4, 3, 6 };

 

            int max = new RunClass().MaxPartsNumber(array);

            Console.WriteLine(max);

 

            Console.ReadLine();

        }

 

        public int MaxPartsNumber(int[] array)

        {

            List<int> list = new List<int>();

            list.AddRange(array);

 

            int sum = 0;

            foreach (int i in array)

            {

                sum += i;

            }

 

            for (int i = array.Length; i >0; i--)

            {

                if (sum % i == 0)

                {

                    if (IfExist(list, sum / i, sum / i))

                    {

                        return i;

                    }

                }

            }

 

            return 1;

        }

 

        private bool IfExist(List<int> rootList, int number, int orginalNumber)

        {

            if (rootList.Count == 0 && number==orginalNumber)

            {

                return true;

            }

 

            bool ifExist = false;

 

            for (int i=0; i<rootList.Count;i++)

            {

                List<int> childList = new List<int>();

 

                for (int j = 0; j < rootList.Count; j++)

                {

                    if (j != i)

                    {

                        childList.Add(rootList[j]);

                    }

                }

 

                if (rootList[i] == number)

                {                 

                    ifExist = ifExist || IfExist(childList, orginalNumber, orginalNumber);

                }

                else if (rootList[i] < number)

                {

                    ifExist = ifExist || IfExist(childList, number - rootList[i], orginalNumber);

                }

            }

            return ifExist;

        }

    }

 

   

}

 

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值