[Algo] 87. Max Product Of Cutting Rope

Given a rope with positive integer-length n, how to cut the rope into m integer-length parts with length p[0], p[1], ...,p[m-1], in order to get the maximal product of p[0]*p[1]* ... *p[m-1]? is determined by you and must be greater than 0 (at least one cut must be made). Return the max product you can have.

Assumptions

  • n >= 2

Examples

  • n = 12, the max product is 3 * 3 * 3 * 3 = 81(cut the rope into 4 pieces with length of each is 3).

public class Solution {
  public int maxProduct(int length) {
    // Write your solution here
    int[] arr = new int[length + 1];
    arr[0] = 0;
    for (int i = 0; i < arr.length; i++) {
      for (int j = 0; j < i; j++) {
        // arr[i] = Math.max(arr[i], Math.max(i, arr[j] * (i - j)));
        arr[i] = Math.max(arr[i], (i - j) * Math.max(j, arr[j]));
      }
    }
    return arr[length];
  }
}

猜你喜欢

转载自www.cnblogs.com/xuanlu/p/12348426.html