📌  相关文章
📜  在小于或等于N的数字中查找数字的最大乘积

📅  最后修改于: 2021-04-23 22:41:41             🧑  作者: Mango

给定整数N> 0 ,任务是在小于或等于N的数字中找到数字的最大乘积。
例子:

方法:也可以使用本文中描述的方法解决此问题,将下限设为1 ,将上限设为N。解决此问题的另一种方法是使用递归。递归的条件如下:

  • 如果N = 0,则返回1
  • 如果N <10,则返回N。
  • 否则,返回max(maxProd(N / 10)*(N%10),maxProd((N / 10)– 1)* 9

在递归的每个步骤中,采用最后一位或9位来最大化位的乘积。
下面是上述方法的实现:

C++
// C++ implementation of the approach
#include 
using namespace std;
 
// Function that returns the maximum product of
// digits among numbers less than or equal to N
int maxProd(int N)
{
    if (N == 0)
        return 1;
    if (N < 10)
        return N;
    return max(maxProd(N / 10) * (N % 10),
               maxProd(N / 10 - 1) * 9);
}
 
// Driver code
int main()
{
    int N = 390;
    cout << maxProd(N);
 
    return 0;
}


Java
// Java implementation of the approach
import java.io.*;
 
class GFG
{
     
// Function that returns the maximum product of
// digits among numbers less than or equal to N
static int maxProd(int N)
{
    if (N == 0)
        return 1;
    if (N < 10)
        return N;
    return Math.max(maxProd(N / 10) * (N % 10),
            maxProd(N / 10 - 1) * 9);
}
 
// Driver code
public static void main (String[] args)
{
    int N = 390;
    System.out.println (maxProd(N));
}
}
 
// This code is contributed by ajit.


Python3
# Python3 implementation of the approach
 
# Function that returns the maximum product of
# digits among numbers less than or equal to N
def maxProd(N):
 
    if (N == 0):
        return 1
    if (N < 10):
        return N
    return max(maxProd(N // 10) * (N % 10),
               maxProd(N // 10 - 1) * 9)
 
# Driver code
N = 390
print(maxProd(N))
 
# This code is contributed by mohit kumar


C#
// C# implementation of the approach
using System;
 
class GFG
{
         
// Function that returns the maximum product of
// digits among numbers less than or equal to N
static int maxProd(int N)
{
    if (N == 0)
        return 1;
    if (N < 10)
        return N;
    return Math.Max(maxProd(N / 10) * (N % 10),
            maxProd(N / 10 - 1) * 9);
}
 
// Driver code
static public void Main ()
{
    int N = 390;
    Console.WriteLine(maxProd(N));
}
}
 
// This code is contributed by Tushil..


PHP


Javascript


输出:
216