Maximum Product Cutting

Given a rope of length n meters, cut the rope in different parts of integer lengths in a way that maximizes product of lengths of all parts. You must make at least one cut. Assume that the length of rope is more than 2 meters.

Examples:

Input: n = 2
Output: 1 (Maximum obtainable product is 1*1)

Input: n = 3
Output: 2 (Maximum obtainable product is 1*2)

Input: n = 4
Output: 4 (Maximum obtainable product is 2*2)

Input: n = 5
Output: 6 (Maximum obtainable product is 2*3)

Input: n = 10
Output: 36 (Maximum obtainable product is 3*3*4)
class Solution {
    // Given n>=2
    public static int maxProd(int n) {
        int dp[] = new int[n + 1];
        dp[1] = 1;
        dp[2] = 1;
        // dp[i] -> max product we can get with length i
        for (int i = 3; i <= n; i++) {
            // min multiplication will be 1 ,when rod cut into peices of 1
            dp[i] = 1;
            for (int j = 1; j < i; j++)
                dp[i] = Math.max(dp[i], Math.max(j, dp[j]) * (i - j));
        }
        return dp[n];
    }
}

Last updated