
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
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
#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
- Related Articles
- Find all factorial numbers less than or equal to n in C++
- Print all prime numbers less than or equal to N in C++
- Print all Semi-Prime Numbers less than or equal to N in C++
- Find maximum sum array of length less than or equal to m in C++
- Find three integers less than or equal to N such that their LCM is maximum - C++
- Find three integers less than or equal to N such that their LCM is maximum in C++
- Find Multiples of 2 or 3 or 5 less than or equal to N in C++
- Maximum product from array such that frequency sum of all repeating elements in product is less than or equal to 2 * k in C++
- Recursive program to print all numbers less than N which consist of digits 1 or 3 only in C++
- How to find numbers in an array that are greater than, less than, or equal to a value in java?
- Maximum sum subarray having sum less than or equal to given sums in C++
- Find unique pairs such that each element is less than or equal to N in C++
- Find maximum number of elements such that their absolute difference is less than or equal to 1 in C++
- Maximum Side Length of a Square with Sum Less than or Equal to Threshold in C++
- Find four factors of N with maximum product and sum equal to N in C++

Advertisements