Maximum sum and product of the M consecutive digits in a number in C++

C++Server Side ProgrammingProgramming

In this problem, we are given a string denoting a number. Our task is to create a program to find the Maximum sum and product of the M consecutive digits in a number in C++.

Problem Description

We find all sequences of M consecutive digits. And return the maximum sum and product.

Let’s take an example to understand the problem,

Input

number = 2379641, M = 4

Output

maxSum = 26maxProd = 1512

Explanation

All subsequences of size 4 are 2379, 3796, 7964, 9641. maxSum = 7 + 9 + 6 + 4 = 26 maxProd = 7 * 9 * 6 * 4 = 1512

Solution Approach

A simple solution to the problem is find all possible consecutive subsequences of size M form the number. Then add and multiply all values of the integer and then return the maximum of all sum and product values.

Example

Program to illustrate the working of our solution,

 Live Demo

#include <iostream>
using namespace std;
int findMaxVal(int x, int y){
   if(x > y)
      return x;
      return y;
}
void calcMaxProductAndSum(string number, int M){
   int N = number.length();
   int maxProd = -1, maxSum = -1;
   int product = 1, sum = 0;
   for (int i = 0; i < N - M; i++){
      product = 1, sum = 0;
      for (int j = i; j < M + i; j++){
         product = product * (number[j] - '0');
         sum = sum + (number[j] - '0');
      }
      maxProd = findMaxVal(maxProd, product);
      maxSum = findMaxVal(maxSum, sum);
   }
   cout<<"The Maximum Product of "<<M<<" consecutive digits in number "<<number<<" is "<<maxProd<<endl;
   cout<<"The Sum Product of "<<M<<" consecutive digits in number "<<number<<" is "<<maxSum;
}
int main() {
   string str = "2379641";
   int m = 4;
   calcMaxProductAndSum(str, m);
}

Output

The Maximum Product of 4 consecutive digits in number 2379641 is 1512
The Sum Product of 4 consecutive digits in number 2379641 is 26
raja
Published on 10-Jul-2020 14:21:47
Advertisements