zoukankan      html  css  js  c++  java
  • 数组分段和最大值的最小值问题

    题目

    给定一个数组,将其分为 k 段,对每一段求和,并求得最大值 max。

    求在所有的分段方案中,max 的最小值。

    代码

    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));
        }
    }
    
  • 相关阅读:
    Ext Form
    Ext中 get、getDom、getCmp的区别
    Ext.state.Manager.setProvider(new Ext.state.CookieProvider())
    Ext BoxComponent
    Ext表单提示方式:msgTarget
    Ext.QuickTips.init()的使用
    Ext.Ajax.Request
    FitLayout
    视图Ext.Viewport和窗口Ext.Window用法
    禁用IE缓存
  • 原文地址:https://www.cnblogs.com/debugxw/p/11461746.html
Copyright © 2011-2022 走看看