Divide Chocolate

You have one chocolate bar that consists of some chunks. Each chunk has its own sweetness given by the array sweetness.

You want to share the chocolate with your K friends so you start cutting the chocolate bar into K+1 pieces using K cuts, each piece consists of some consecutive chunks.

Being generous, you will eat the piece with the minimum total sweetness and give the other pieces to your friends.

Find the maximum total sweetness of the piece you can get by cutting the chocolate bar optimally.

Example 1:

Input: sweetness = [1,2,3,4,5,6,7,8,9], K = 5
Output: 6
Explanation: You can divide the chocolate to [1,2,3], [4,5], [6], [7], [8], [9]

思路:就是求最小的區間和,其他的區間可以> limit,然後用這個區間limit去劃分,最多隻能劃分k次;

也就是二分答案,如果min(A[i]), 可以切n 刀,如果sum(A[i]) ,可以切0刀;也就是二分;

注意cutnum 是最小的區間和,使得切的是k刀;A[i] > limit,直接count++;

class Solution {
    public int maximizeSweetness(int[] sweetness, int K) {
        int minnum = Integer.MAX_VALUE;
        int sum = 0;
        for(int num : sweetness) {
            minnum = Math.min(minnum, num);
            sum += num;
        }
        int start = minnum, end = sum;
        while(start + 1 < end) {
            int mid = start + (end - start) / 2;
            if(cutnum(sweetness, mid) > K) {
                start = mid;
            } else {
                end = mid;
            }
        }
        
        if(cutnum(sweetness, start) > K) {
            return end;
        }
        return start;
    }
    
    private int cutnum(int[] A, int limit) {
        int count = 0;
        int i = 0;
        int cursum = 0;
        while(i < A.length) {
            if(cursum + A[i] <= limit) {
                cursum += A[i];
                i++;
            } else {
                count++;
                cursum = 0;
                i++;
            }
        }
        return count;
    }
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章