Arrange II

You are given a sequence of black and white horses, and a set of K stables numbered 1 to K. You have to accommodate the horses into the stables in such a way that the following conditions are satisfied:

Example:

Input: {WWWB} , K = 2
Output: 0

Explanation:
We have 3 choices {W, WWB}, {WW, WB}, {WWW, B}
for first choice we will get 1*0 + 2*1 = 2.
for second choice we will get 2*0 + 1*1 = 1.
for third choice we will get 3*0 + 0*1 = 0.

Of the 3 choices, the third choice is the best option. 


If a solution is not possible, then return -1

Solution:

Time: O(A^3*B)
Space: O(AB)

public class Solution {
    private int calc(int i, int j, String A) {
        int w = 0;
        int b = 0;
        while (i <= j) {
            char c = A.charAt(i);
            if (c == 'W') {
                w ++;
            } else {
                b ++;
            }
            i ++;
        }
        return w * b;
    }
    
    public int arrange(String A, int B) {
        // dp[i][p] = min product from 0 to i with p stables
        // dp[i][p] = min(dp[j][p - 1] + calc(j, n, 1))
        // dp[i][1] = calc
        // dp[0][p] = 0
        // dp[n - 1][B]
        if (A == null || A.length() == 0 || B == 0) return 0;
        if (B > A.length()) return -1;
        int n = A.length();
        int[][] dp = new int[n][B + 1];
        for (int i = 0; i < n; i ++) {
            dp[i][1] = calc(0, i, A);
        }
        for (int p = 2; p <= B; p ++) {
            dp[0][p] = 0;
        }
        for (int i = 1; i < n; i ++) {
            for (int p = 2; p <= B; p ++) {
                dp[i][p] = Integer.MAX_VALUE;
                for (int k = 0; k < i; k ++) {
                    dp[i][p] = Math.min(dp[i][p], dp[k][p - 1] + calc(k + 1, i, A));
                }
            }
        }
        // for (int[] a : dp) {
        //         System.out.println(Arrays.toString(a));
        // }
        return dp[n - 1][B];
    }
}