Arrays and minimum of the maximum segment

topic

Given an array, which is divided into k sections, the maximum value max for each segment are summed, and determined.

Minimization scheme in all segments, max of.

Code

public class Main {

    public static int getMax(int array[], int n) {
        int max = Integer.MIN_VALUE;
        for (int i = 0; i < n; i++) {
            if (array[i] > max) max = array[i];
        }
        return max;
    }

    public static int getSum(int array[], int n) {
        int total = 0;
        for (int i = 0; i < n; i++)
            total += array[i];
        return total;
    }

    /**
     * 当所有段的最大值为 maxLengthPerPainter 时,返回最少可以将其分为多少段
     */
    public static int getRequiredPainters(int array[], int n, int maxLengthPerPainter) {
        int total = 0, numPainters = 1;
        for (int i = 0; i < n; i++) {
            total += array[i];
            if (total > maxLengthPerPainter) {
                total = array[i];
                numPainters++;
            }
        }
        return numPainters;
    }

    public static int binarySearch(int array[], int n, int k) {
        /**
         * low 代表所有分段中的最小段的值
         * high 代表所有分段中的最大段的值
         */
        int low = getMax(array, n);
        int high = getSum(array, n);

        while (low < high) {
            int mid = low + (high - low) / 2;
            int requiredPainters = getRequiredPainters(array, n, mid);
            if (requiredPainters <= k)
                high = mid;
            else
                low = mid + 1;
        }
        return low;
    }

    public static void main(String[] args) {
        int k = 3;
        int[] a = {9, 4, 5, 12, 3, 5, 8, 11, 0};
        System.out.println(binarySearch(a, a.length, k));
    }
}

Guess you like

Origin www.cnblogs.com/debugxw/p/11461746.html