[343] In an integer of split / cut the rope

Title Description

Given a positive integer n, which is split into at least two positive integers, and the product of those integers maximized. Returns the maximum you can get the product.

Example 1:

Input: 2
Output: 1
explains: 2 = 1 + 1, 1 × 1 = 1.
Example 2:

Input: 10
Output: 36
explains: 10 = 3 + 3 + 4 , 3 × 3 × 4 = 36.

Another description :

You give a string of length n, m please cut the rope section (m, n are integers, n> 1 and m≥1). The length of each segment is referred to as a rope k [0], k [1], ......, k [m]. k [0] * k [1] * ... * k [m] maximum possible product is how much? For example, when the rope length is 8, we cut it into lengths of the three sections 2,3,3, 18 at this time to obtain the maximum product.

Analysis of ideas:

Dynamic programming, the first top-down analysis, the rope length n seek maximum multiplier is f (n), after the knife cut the remaining two lengths and is i ni, then we can continue to break down into sub-problems

When the rope when the length is less than or equal to 3, are not Shear better than, the length = 3 can be used as the input boundary, the optimal solution is less than 3 listed directly, greater than 3 using dynamic programming split into sub-problems.

Code:

  public int integerBreak(int n) {
      if(n < 2){
          return 0;
      }
      if(n == 2){
          return 1;
      }
      if(n == 3){
          return 2;
      }
      
      int[] arr = new int[n+1];
      arr[0] = 0;
      arr[1] = 1;
      arr[2] = 2;
      arr[3] = 3;

      int max = 0;
      for (int i = 4; i <= n ; i++){
          max = 0;
          //当j大于i的一半时,相当于重复了,所以j <= i/2
          for (int j = 1; j <= i/2 ; j++){
              int temp = arr[j] * arr[i-j];
              if(max < temp){
                  max = temp;
              } 
          } 
        arr[i] = max;
      }
    
    return arr[n];
    }

Complexity Analysis

 O (nlog n)

Published 28 original articles · won praise 9 · views 4649

Guess you like

Origin blog.csdn.net/chixi123/article/details/104041429