📜  最大产品切割| DP-36

📅  最后修改于: 2021-09-17 07:23:53             🧑  作者: Mango

给定一根长度为 n 米的绳索,将绳索切割成整数长度的不同部分,以最大化所有部分长度的乘积。您必须至少进行一次切割。假设绳子的长度超过 2 米。
例子:

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)

1) 最优子结构:
这个问题类似于杆切割问题。我们可以通过在不同位置进行切割并比较切割后获得的值来获得最大乘积。我们可以为切割后获得的一块递归调用相同的函数。
设 maxProd(n) 是长度为 n 的绳索的最大乘积。 maxProd(n) 可以写成如下。
maxProd(n) = max(i*(ni), maxProdRec(ni)*i) 对于 {1, 2, 3 .. n} 中的所有 i
2) 重叠子问题
以下是问题的简单递归实现。实现只是简单地遵循上面提到的递归结构。

C++
// A Naive Recursive method to find maximum product
#include 
using namespace std;
 
// Utility function to get the maximum of two and three integers
int max(int a, int b) { return (a > b)? a : b;}
int max(int a, int b, int c) { return max(a, max(b, c));}
 
// The main function that returns maximum product obtainable
// from a rope of length n
int maxProd(int n)
{
    // Base cases
    if (n == 0 || n == 1) return 0;
 
    // Make a cut at different places and take the maximum of all
    int max_val = 0;
    for (int i = 1; i < n; i++)
      max_val = max(max_val, i*(n-i), maxProd(n-i)*i);
 
    // Return the maximum of all values
    return max_val;
}
 
/* Driver program to test above functions */
int main()
{
    cout << "Maximum Product is " << maxProd(10);
    return 0;
}


Java
// Java program to find maximum product
import java.io.*;
 
class GFG {
 
    // The main function that returns
    // maximum product obtainable from
    // a rope of length n
    static int maxProd(int n)
    {
        // Base cases
        if (n == 0 || n == 1) return 0;
 
        // Make a cut at different places
        // and take the maximum of all
        int max_val = 0;
        for (int i = 1; i < n; i++)
        max_val = Math.max(max_val,
                  Math.max(i * (n - i),
                   maxProd(n - i) * i));
 
        // Return the maximum of all values
        return max_val;
    }  
 
    /* Driver program to test above functions */
    public static void main(String[] args)
    {
        System.out.println("Maximum Product is "
                            + maxProd(10));
    }
}
// This code is contributed by Prerna Saini


Python3
# The main function that returns maximum
# product obtainable from a rope of length n
 
def maxProd(n):
     
    # Base cases
    if (n == 0 or n == 1):
        return 0
  
    # Make a cut at different places
    # and take the maximum of all
    max_val = 0
    for i in range(1, n - 1):
        max_val = max(max_val, max(i * (n - i), maxProd(n - i) * i))
  
    #Return the maximum of all values
    return max_val;
 
  
# Driver program to test above functions
print("Maximum Product is ", maxProd(10));
     
# This cide is contributed
# by Sumit Sudhakar


C#
// C# program to find maximum product
using System;
 
class GFG {
     
    // The main function that returns 
    // the max possible product
    static int maxProd(int n)
    {
 
        // n equals to 2 or 3 must
        // be handled explicitly
        if (n == 2 || n == 3)
            return (n - 1);
 
        // Keep removing parts of size
        // 3 while n is greater than 4
        int res = 1;
        while (n > 4) {
            n -= 3;
 
            // Keep multiplying 3 to res
            res *= 3;
        }
 
        // The last part multiplied
        // by previous parts
        return (n * res);
    }
 
    // Driver code
    public static void Main()
    {
        Console.WriteLine("Maximum Product is "
                                + maxProd(10));
    }
}
 
// This code is contributed by Sam007


PHP


Javascript


C
// A Dynamic Programming solution for Max Product Problem
int maxProd(int n)
{
   int val[n+1];
   val[0] = val[1] = 0;
  
   // Build the table val[] in bottom up manner and return
   // the last entry from the table
   for (int i = 1; i <= n; i++)
   {
      int max_val = 0;
      for (int j = 1; j <= i/2; j++)
         max_val = max(max_val, (i-j)*j, j*val[i-j]);
      val[i] = max_val;
   }
   return val[n];
}


C++
#include 
using namespace std;
 
/* The main function that returns the max possible product */
int maxProd(int n)
{
   // n equals to 2 or 3 must be handled explicitly
   if (n == 2 || n == 3) return (n-1);
 
   // Keep removing parts of size 3 while n is greater than 4
   int res = 1;
   while (n > 4)
   {
       n -= 3;
       res *= 3; // Keep multiplying 3 to res
   }
   return (n * res); // The last part multiplied by previous parts
}
 
/* Driver program to test above functions */
int main()
{
    cout << "Maximum Product is " << maxProd(10);
    return 0;
}


Java
// Java program to find maximum product
import java.io.*;
 
class GFG {
 
    /* The main function that returns the
    max possible product */
    static int maxProd(int n)
    {
     
    // n equals to 2 or 3 must be handled
    // explicitly
    if (n == 2 || n == 3) return (n-1);
 
    // Keep removing parts of size 3
    // while n is greater than 4
    int res = 1;
    while (n > 4)
    {
        n -= 3;
         
        // Keep multiplying 3 to res
        res *= 3;
    }
     
    // The last part multiplied by
    // previous parts
    return (n * res);
    }
 
    /* Driver program to test above functions */
    public static void main(String[] args)
    {
        System.out.println("Maximum Product is "
                            + maxProd(10));
    }  
}
// This code is contributed by Prerna Saini


Python3
# The main function that returns the
# max possible product
 
def maxProd(n):
     
    # n equals to 2 or 3 must
    # be handled explicitly
    if (n == 2 or n == 3):
        return (n - 1)
  
    # Keep removing parts of size 3
    # while n is greater than 4
    res = 1
    while (n > 4):
        n -= 3;
          
        # Keep multiplying 3 to res
        res *= 3;
     
    # The last part multiplied
    # by previous parts
    return (n * res)
 
# Driver program to test above functions
print("Maximum Product is ", maxProd(10));
     
# This code is contributed
# by Sumit Sudhakar


C#
// C# program to find maximum product
using System;
 
class GFG {
 
    // The main function that returns
    // maximum product obtainable from
    // a rope of length n
    static int maxProd(int n)
    {
        // Base cases
        if (n == 0 || n == 1)
            return 0;
 
        // Make a cut at different places
        // and take the maximum of all
        int max_val = 0;
        for (int i = 1; i < n; i++)
            max_val = Math.Max(max_val,
                    Math.Max(i * (n - i),
                     maxProd(n - i) * i));
 
        // Return the maximum of all values
        return max_val;
    }
 
    // Driver code
    public static void Main()
     {
        Console.WriteLine("Maximum Product is "
                                + maxProd(10));
     }
}
 
// This code is contributed by Sam007


PHP
 4)
{
    $n = $n - 3;
     
    // Keep multiplying 3 to res
    $res = $res * 3;
}
 
// The last part multiplied
// by previous parts
return ($n * $res);
}
 
// Driver code
echo ("Maximum Product is ");
echo(maxProd(10));
 
// This code is contributed
// by Shivi_Aggarwal
?>


Javascript


输出:

Maximum Product is 36

考虑到上述实现,以下是长度为 5 的 Rope 的递归树。

最大产品切割

在上面的部分递归树中,mP(3) 被求解了两次。我们可以看到,有很多子问题被一次又一次地解决了。由于再次调用相同的子问题,因此该问题具有重叠子问题的属性。所以这个问题具有动态规划问题的两个属性(见this和this)。与其他典型的动态规划 (DP) 问题一样,可以通过以自下而上的方式构造临时数组 val[] 来避免对相同子问题的重新计算。

C

// A Dynamic Programming solution for Max Product Problem
int maxProd(int n)
{
   int val[n+1];
   val[0] = val[1] = 0;
  
   // Build the table val[] in bottom up manner and return
   // the last entry from the table
   for (int i = 1; i <= n; i++)
   {
      int max_val = 0;
      for (int j = 1; j <= i/2; j++)
         max_val = max(max_val, (i-j)*j, j*val[i-j]);
      val[i] = max_val;
   }
   return val[n];
}

动态规划解决方案的时间复杂度为 O(n^2) 并且需要 O(n) 额外空间。
一个棘手的解决方案:
如果我们看到这个问题的一些例子,我们可以很容易地观察到以下模式。
当尺寸大于4时,重复切割尺寸为3的零件,保持最后的零件尺寸为2或3或4,可以获得最大乘积。例如,n = 10,通过3、3、3获得最大乘积, 4.对于n = 11,最大乘积由3, 3, 3, 2得到。以下是这种方法的实现。

C++

#include 
using namespace std;
 
/* The main function that returns the max possible product */
int maxProd(int n)
{
   // n equals to 2 or 3 must be handled explicitly
   if (n == 2 || n == 3) return (n-1);
 
   // Keep removing parts of size 3 while n is greater than 4
   int res = 1;
   while (n > 4)
   {
       n -= 3;
       res *= 3; // Keep multiplying 3 to res
   }
   return (n * res); // The last part multiplied by previous parts
}
 
/* Driver program to test above functions */
int main()
{
    cout << "Maximum Product is " << maxProd(10);
    return 0;
}

Java

// Java program to find maximum product
import java.io.*;
 
class GFG {
 
    /* The main function that returns the
    max possible product */
    static int maxProd(int n)
    {
     
    // n equals to 2 or 3 must be handled
    // explicitly
    if (n == 2 || n == 3) return (n-1);
 
    // Keep removing parts of size 3
    // while n is greater than 4
    int res = 1;
    while (n > 4)
    {
        n -= 3;
         
        // Keep multiplying 3 to res
        res *= 3;
    }
     
    // The last part multiplied by
    // previous parts
    return (n * res);
    }
 
    /* Driver program to test above functions */
    public static void main(String[] args)
    {
        System.out.println("Maximum Product is "
                            + maxProd(10));
    }  
}
// This code is contributed by Prerna Saini

蟒蛇3

# The main function that returns the
# max possible product
 
def maxProd(n):
     
    # n equals to 2 or 3 must
    # be handled explicitly
    if (n == 2 or n == 3):
        return (n - 1)
  
    # Keep removing parts of size 3
    # while n is greater than 4
    res = 1
    while (n > 4):
        n -= 3;
          
        # Keep multiplying 3 to res
        res *= 3;
     
    # The last part multiplied
    # by previous parts
    return (n * res)
 
# Driver program to test above functions
print("Maximum Product is ", maxProd(10));
     
# This code is contributed
# by Sumit Sudhakar

C#

// C# program to find maximum product
using System;
 
class GFG {
 
    // The main function that returns
    // maximum product obtainable from
    // a rope of length n
    static int maxProd(int n)
    {
        // Base cases
        if (n == 0 || n == 1)
            return 0;
 
        // Make a cut at different places
        // and take the maximum of all
        int max_val = 0;
        for (int i = 1; i < n; i++)
            max_val = Math.Max(max_val,
                    Math.Max(i * (n - i),
                     maxProd(n - i) * i));
 
        // Return the maximum of all values
        return max_val;
    }
 
    // Driver code
    public static void Main()
     {
        Console.WriteLine("Maximum Product is "
                                + maxProd(10));
     }
}
 
// This code is contributed by Sam007

PHP

 4)
{
    $n = $n - 3;
     
    // Keep multiplying 3 to res
    $res = $res * 3;
}
 
// The last part multiplied
// by previous parts
return ($n * $res);
}
 
// Driver code
echo ("Maximum Product is ");
echo(maxProd(10));
 
// This code is contributed
// by Shivi_Aggarwal
?>

Javascript


输出:

Maximum Product is 36

如果您希望与专家一起参加现场课程,请参阅DSA 现场工作专业课程学生竞争性编程现场课程