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

Given a number in the form of a string. The task is to find the maximum sum and product of m consecutive digits that are taken from the number string.

Examples:

Input: N = 3675356291, m = 5
Output: 3150
There are 6 sequences of 5 digits 36753, 67535, 75356, 53562, 35629, 56291
6 x 7 x 5 x 3 x 5 gives the maximum product.



Input: N = 2709360626, m = 5
Output: 0
Since each sequence of consecutive 5 digits will contain a 0 so each time product will be zero so
the maximum product is zero.

Naive Approach:

  1. Take all possible consequtive sequences of m characters from the given string.
  2. Add them and Multiply them by changing the characters into integers.
  3. Compare the product and sum of each sequence and find the maximum product and sum.

Below is the implementation of the above approach:

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ implemenattion of the above approach
#include <bits/stdc++.h>
using namespace std;
  
// Function to find the maximum product
void maxProductSum(string str, int m)
{
    int n = str.length();
    int maxProd = INT_MIN, maxSum = INT_MIN;
    for (int i = 0; i < n - m; i++) {
        int product = 1, sum = 0;
  
        for (int j = i; j < m + i; j++) {
            product = product * (str[j] - '0');
            sum = sum + (str[j] - '0');
        }
  
        maxProd = max(maxProd, product);
        maxSum = max(maxSum, sum);
    }
    cout << "Maximum Product = " << maxProd;
    cout << "\nMaximum Sum = " << maxSum;
}
  
// Driver code
int main()
{
    string str = "3675356291";
    int m = 5;
  
    maxProductSum(str, m);
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java implemenattion of the above approach
  
import java.io.*;
  
class GFG {
   
  
// Function to find the maximum product
 static void maxProductSum(String str, int m)
{
    int n = str.length();
    int maxProd = Integer.MIN_VALUE, maxSum = Integer.MIN_VALUE;
    for (int i = 0; i < n - m; i++) {
        int product = 1, sum = 0;
  
        for (int j = i; j < m + i; j++) {
            product = product * (str.charAt(j) - '0');
            sum = sum + (str.charAt(j) - '0');
        }
  
        maxProd = Math.max(maxProd, product);
        maxSum = Math.max(maxSum, sum);
    }
    System.out.println("Maximum Product = " + maxProd);
    System.out.print( "\nMaximum Sum = " + maxSum);
}
  
// Driver code
  
    public static void main (String[] args) {
        String str = "3675356291";
    int m = 5;
  
    maxProductSum(str, m);
    }
}
// This code is contributed by anuj_67..

chevron_right


Python 3

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python implementation of
# above approach
import sys
  
# Function to find the maximum product
def maxProductSum(string, m) :
  
    n = len(string)
    maxProd , maxSum = (-(sys.maxsize) - 1
                        -(sys.maxsize) - 1)
  
    for i in range(n - m) :
        product, sum = 1, 0
  
        for j in range(i, m + i) :
            product = product * (ord(string[j]) -
                                 ord('0'))
            sum = sum + (ord(string[j]) - 
                         ord('0'))
  
        maxProd = max(maxProd, product)
        maxSum = max(maxSum, sum)
  
    print("Maximum Product =", maxProd)
    print("Maximum sum =", maxSum)
      
# Driver code
if __name__ == "__main__" :
  
    string = "3675356291"
    m = 5
    maxProductSum(string, m)
          
# This code is contributed by ANKITRAI1

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# implemenattion of the above approach
using System;
class GFG 
{
      
// Function to find the maximum product
static void maxProductSum(string str, int m)
{
    int n = str.Length;
    int maxProd = int.MinValue,
        maxSum = int.MinValue;
    for (int i = 0; i < n - m; i++) 
    {
        int product = 1, sum = 0;
  
        for (int j = i; j < m + i; j++) 
        {
            product = product * (str[j] - '0');
            sum = sum + (str[j] - '0');
        }
  
        maxProd = Math.Max(maxProd, product);
        maxSum = Math.Max(maxSum, sum);
    }
    Console.WriteLine("Maximum Product = " + maxProd);
    Console.Write( "\nMaximum Sum = " + maxSum);
}
  
// Driver code
public static void Main () 
{
    string str = "3675356291";
    int m = 5;
      
    maxProductSum(str, m);
}
}
  
// This code is contributed 
// by Akanksha Rai

chevron_right


PHP

filter_none

edit
close

play_arrow

link
brightness_4
code

<?php
// PHP implemenattion of the above approach 
  
// Function to find the maximum product 
function maxProductSum($str, $m
    $n = strlen($str); 
    $maxProd = PHP_INT_MIN;
    $maxSum = PHP_INT_MIN; 
    for ($i = 0; $i < ($n - $m); $i++) 
    
        $product = 1;
        $sum = 0; 
  
        for ($j = $i; $j < ($m + $i); $j++) 
        
            $product = $product
                      ($str[$j] - '0'); 
            $sum = $sum + ($str[$j] - '0'); 
        
  
        $maxProd = max($maxProd, $product); 
        $maxSum = max($maxSum, $sum); 
    
    echo "Maximum Product = " ,$maxProd
    echo "\nMaximum Sum = " , $maxSum
  
// Driver code 
$str = "3675356291"
$m = 5; 
  
maxProductSum($str, $m); 
  
// This code is contributed by @Tushil.
?>

chevron_right


Output:

Maximum Product = 3150
Maximum Sum = 26

Efficient Approach: The idea is to use the Sliding Window concept . First find the sum and product of M consecutive digits and update the maxProd and maxSum.
Then start traversing from Mth index and add current digit to the sum and subtract str[i-M] from the sum i.e. considering only M elements/digits. Similarly for the product. And keep updating the maxSum and maxProd.

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ implemenattion of the above approach
#include <bits/stdc++.h>
using namespace std;
  
// Function to find the maximum product and sum
void maxProductSum(string str, int m)
{
    int n = str.length();
    int product = 1, sum = 0;
  
    // find the sum and product of first K digits
    for (int i = 0; i < m; i++) {
        sum += (str[i] - '0');
        product *= (str[i] - '0');
    }
  
    // Update maxProd and maxSum
    int maxProd = product;
    int maxSum = sum;
  
    // Start traversing the next element
    for (int i = m; i < n; i++) {
  
        // Multiply with the current digit and divide by
        // the first digit of previous window
        product = product * (str[i] - '0') / ((str[i - m]) - '0');
  
        // Add the current digit and subtract
        // the first digit of previous window
        sum = sum + (str[i] - '0') - ((str[i - m]) - '0');
  
        // Update maxProd and maxSum
        maxProd = max(maxProd, product);
        maxSum = max(maxSum, sum);
    }
  
    cout << "Maximum Product = " << maxProd;
    cout << "\nMaximum Sum = " << maxSum;
}
  
// Driver code
int main()
{
    string str = "3675356291";
    int m = 5;
  
    maxProductSum(str, m);
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java implemenattion of the above approach
import java.util.Arrays; 
import java.io.*;
  
class GFG {
      
// Function to find the maximum product and sum
static void maxProductSum(String str, int m)
{
    int n = str.length();
    int product = 1, sum = 0;
  
    // find the sum and product of first K digits
    for (int i = 0; i < m; i++) 
    {
        sum += (str.charAt(i) - '0');
        product *= (str.charAt(i) - '0');
    }
  
    // Update maxProd and maxSum
    int maxProd = product;
    int maxSum = sum;
  
    // Start traversing the next element
    for (int i = m; i < n; i++) 
    {
  
        // Multiply with the current digit and divide by
        // the first digit of previous window
        product = product * (str.charAt(i) - '0') / ((str.charAt(i-m)) - '0');
  
        // Add the current digit and subtract
        // the first digit of previous window
        sum = sum + (str.charAt(i) - '0') - ((str.charAt(i-m)) - '0');
  
        // Update maxProd and maxSum
        maxProd = Math.max(maxProd, product);
        maxSum = Math.max(maxSum, sum);
    }
  
    System.out.println("Maximum Product = " + maxProd);
    System.out.println("\nMaximum Sum = " + maxSum);
}
  
// Driver code
    public static void main (String[] args) {
        String str = "3675356291";
        int m = 5;
        maxProductSum(str, m);
    }
}
  
// This code is contributed 
// by ajit

chevron_right


Python 3

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python 3 implemenattion of the above approach
  
# Function to find the maximum product and sum
def maxProductSum(str, m):
  
    n = len(str)
    product = 1
    sum = 0
  
    # find the sum and product of first K digits
    for i in range(m):
        sum += (ord(str[i]) - ord('0'))
        product *= (ord(str[i]) - ord('0'))
  
    # Update maxProd and maxSum
    maxProd = product
    maxSum = sum
  
    # Start traversing the next element
    for i in range(m, n) :
  
        # Multiply with the current digit and divide 
        # by the first digit of previous window
        product = (product * (ord(str[i]) - ord('0')) // 
                            ((ord(str[i - m])) - ord('0')))
  
        # Add the current digit and subtract
        # the first digit of previous window
        sum = (sum + (ord(str[i]) - ord('0')) - 
                    ((ord(str[i - m])) - ord('0')))
  
        # Update maxProd and maxSum
        maxProd = max(maxProd, product)
        maxSum = max(maxSum, sum)
  
    print("Maximum Product =", maxProd)
    print("Maximum Sum =", maxSum)
  
# Driver code
if __name__ == "__main__":
      
    str = "3675356291"
    m = 5
  
    maxProductSum(str, m)
  
# This code is contributed by ita_c

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# implemenattion of the above approach
using System;
  
class GFG
{
// Function to find the maximum product and sum
static void maxProductSum(string str, int m)
{
    int n = str.Length;
    int product = 1, sum = 0;
  
    // find the sum and product of first K digits
    for (int i = 0; i < m; i++) 
    {
        sum += (str[i] - '0');
        product *= (str[i] - '0');
    }
  
    // Update maxProd and maxSum
    int maxProd = product;
    int maxSum = sum;
  
    // Start traversing the next element
    for (int i = m; i < n; i++) 
    {
  
        // Multiply with the current digit and divide by
        // the first digit of previous window
        product = product * (str[i] - '0') / ((str[i - m]) - '0');
  
        // Add the current digit and subtract
        // the first digit of previous window
        sum = sum + (str[i] - '0') - ((str[i - m]) - '0');
  
        // Update maxProd and maxSum
        maxProd = Math.Max(maxProd, product);
        maxSum = Math.Max(maxSum, sum);
    }
  
    Console.Write("Maximum Product = " + maxProd);
    Console.Write("\nMaximum Sum = " + maxSum);
}
  
// Driver code
public static void Main()
{
    string str = "3675356291";
    int m = 5;
  
    maxProductSum(str, m);
}
}
  
// This code is contributed 
// by Akanksha Rai

chevron_right


PHP

filter_none

edit
close

play_arrow

link
brightness_4
code

<?php
// PHP implemenattion of the above approach 
  
// Function to find the maximum
// product and sum 
function maxProductSum($str, $m
    $n = strlen($str); 
    $product = 1;
    $sum = 0; 
      
    // find the sum and product of
    // first K digits 
    for ($i = 0; $i < $m; $i++)
    
        $sum += ($str[$i] - '0'); 
        $product *= ($str[$i] - '0'); 
    
  
    // Update maxProd and maxSum 
    $maxProd = $product
    $maxSum = $sum
  
    // Start traversing the next element 
    for ($i = $m; $i < $n; $i++)
    
  
        // Multiply with the current digit and divide 
        // by the first digit of previous window 
        $product = $product * ($str[$i] - '0') / 
                             (($str[$i - $m]) - '0'); 
  
        // Add the current digit and subtract 
        // the first digit of previous window 
        $sum = $sum + ($str[$i] - '0') - 
                     (($str[$i - $m]) - '0'); 
  
        // Update maxProd and maxSum 
        $maxProd = max($maxProd, $product); 
        $maxSum = max($maxSum, $sum); 
    
  
    echo "Maximum Product = " , $maxProd
    echo "\nMaximum Sum = " , $maxSum
  
// Driver code 
$str = "3675356291"
$m = 5; 
maxProductSum($str, $m); 
  
// This code is contributed by ajit
?>

chevron_right


Output:

Maximum Product = 3150
Maximum Sum = 26


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.