zoukankan      html  css  js  c++  java
  • [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
        if (length == 0 || length == 1) {
          return 0;
        }
        int[] cutArr = new int[length + 1];
        cutArr[1] = 0;
        for (int i = 2; i <= length; i++) {
          for (int j = 1; j < i; j++) {
            int curMax = Math.max((i - j) * j, cutArr[i - j] * j);
            cutArr[i] = Math.max(cutArr[i], curMax);
          }
        }
        return cutArr[length];
      }
    }

    DFS

    public class Solution {
      public int maxProduct(int length) {
        // Write your solution here
        if (length == 0 || length == 1) {
          return 0;
        }
        int res = 0;
        for (int i = 1; i < length; i++) {
          int curMax = Math.max(i * (length - i), i * maxProduct(length - i));
          res = Math.max(res, curMax);
        }
        return res;
      }
    }
  • 相关阅读:
    APUE.3源码编译(Ubuntu16.04)
    《UNIX环境高级编程》(第三版)阅读笔记---2018-5-9
    css回归之用户界面
    css回归之文本
    js回归之字符串
    js回归之BOM
    js回归之事件
    百度前端面试总结
    书单
    剑指offer做题收获之一:补码
  • 原文地址:https://www.cnblogs.com/xuanlu/p/12348426.html
Copyright © 2011-2022 走看看