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]

Example 2:

Input: sweetness = [5,6,7,8,9,1,2,3,4], K = 8
Output: 1
Explanation: There is only one way to cut the bar into 9 pieces.

Example 3:

Input: sweetness = [1,2,2,1,2,2,1,2,2], K = 2
Output: 5
Explanation: You can divide the chocolate to [1,2,2], [1,2,2], [1,2,2]

 

Constraints:


Solution:

DP: TLE

class Solution {   
    Integer[][] dp;
    
    public int maximizeSweetness(int[] sweetness, int K) {
        int n = sweetness.length;
        if (n == 0) return 0;
        dp = new Integer[n + 1][K + 1];
        return helper(sweetness, 0, 0, K + 1); 
    }
    
    private int helper(int[] arr, int s, int p, int k) {
        if (dp[s][p] != null) return dp[s][p];
        if (p == k - 1 && s < arr.length) {
            int sum = 0;
            for (int i = s; i < arr.length; i ++) {
                sum += arr[i];
            }
            return dp[s][p] = sum;
        }
        int curr = 0;
        int ret = Integer.MIN_VALUE;
        for (int i = s; i < arr.length; i ++) {
            curr += arr[i];
            int next = helper(arr, i + 1, p + 1, k);
            ret = Math.max(ret, Math.min(curr, next));
        }
        return dp[s][p] = ret;                
    }
}

Binary search:

class Solution {       
    public int maximizeSweetness(int[] sweetness, int K) {
        int n = sweetness.length;
        if (n == 0) return 0;
        int left = 1, right = 100000 * 10000;
        while (left <= right) {
            int mid = (left + right) / 2;
            // can divide to more than K people
            // meaning mid is too small
            if (helper(sweetness, mid) > K) {
                left = mid + 1;
            } else {
                right = mid - 1;
            }
        }
        return left;        
    }
    
    private int helper(int[] arr, int max) {
        int n = 0;
        int curr = 0;
        for (int i = 0; i < arr.length; i ++) {
            if (curr + arr[i] <= max) {
                curr += arr[i];
            } else {
                n ++;
                curr = 0;
            }
        }
        return n;
    }
}