Find maximum product of digits among numbers less than or equal to N in C++


Suppose, we have one integer N > 0. The task is to find the maximum product of digits among numbers less than or equal to N. If the N is 390, then the result is 216, as the number 389 is making maximum product 3 * 8 * 9 = 216.

To solve this problem, we will use the recursive approach. So if N = 0, then return 1, if the number N < 10, then return N, otherwise return max(max_product(N/10) * (N mod 10), max_product((N/10) - 1)*9)

Example

 Live Demo

#include<iostream>
using namespace std;
int max_product(int N) {
   if (N == 0)
      return 1;
   if (N < 10)
      return N;
   return max(max_product(N / 10) * (N % 10), max_product(N / 10 - 1) * 9);
}
int main() {
   int N = 432;
   cout << "Maximum product is: " << max_product(N);
}

Output

Maximum product is: 243

Updated on: 19-Dec-2019

286 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements