将数组除以最小数量的数组,其总和小于或等于给定数字

时间:2017-03-10 08:33:55

标签: c# algorithm

如果数组是:[10,10,10,20,20,30,39,50,50]

maxSum是80

该函数应该返回一个列表,该列表的总和小于或等于80的数组最少(在这种情况下是包含三个数组的列表):

array1:[10,20,50](sum = 80)

array2:[10,20,50](总和= 80)

array3:[10,30,39](sum = 79)

我创建了一个近似算法,但是有些情况下,以下代码创建的数组多于最优解。你能帮我找一个能找到最佳解决方案的算法吗?

    // This is my code:
    private List<Shipment> GetShipmentsByMaxSum(double[] orderedWeights, double maxSum)
    {
        List<Shipment> result = new List<Shipment>();
        Shipment shipment = new Shipment();
        double weight = 0;

        for (int i = 0; i < orderedWeights.Length; i++)
        {
            shipment.Weights.Add(orderedWeights[i]);
            weight += orderedWeights[i];

            double nextWeight = weight;
            if (i + 1 < orderedWeights.Length)
            {
                nextWeight += orderedWeights[i + 1];
            }

            if (nextWeight > maxSum || i + 1 >= orderedWeights.Length)
            {
                result.Add(shipment);
                shipment = new Shipment();
                weight = 0;
            }
        }

        return result;
    }

0 个答案:

没有答案