📌  相关文章
📜  一个数中M个连续数字的最大和与乘积

📅  最后修改于: 2022-05-13 01:57:07.773000             🧑  作者: Mango

一个数中M个连续数字的最大和与乘积

给定一个字符串形式的数字。任务是找到从数字字符串中取出的 m 个连续数字的最大和和乘积。
例子:

天真的方法:

  1. 从给定的字符串中取出所有可能的连续 m 个字符序列。
  2. 通过将字符更改为整数来将它们相加并相乘。
  3. 比较每个序列的乘积和总和,找到最大的乘积和总和。

下面是上述方法的实现:

C++
// Code is Improved by Surya Prakash Sharma
 
// C++ implementation of the above approach
#include 
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 = "3605356297";
    int m = 3;
 
    maxProductSum(str, m);
}


Java
// Code is Improved by Surya Prakash Sharma
 
 // Java implementation 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 = "3605356297";
    int m = 3;
 
    maxProductSum(str, m);
    }
}
// This code is contributed by anuj_67..


Python 3
# Code is Improved by Surya Prakash Sharma
 
# 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+1) :
        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 = "3605356297"
    m = 3
    maxProductSum(string, m)
         
# This code is contributed by ANKITRAI1


C#
// Code is Improved by Surya Prakash Sharma
 
// C# implementation 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 = "3605356297";
    int m = 3;
     
    maxProductSum(str, m);
}
}
 
// This code is contributed
// by Akanksha Rai


PHP


Javascript


C++
// Code Improved By Surya Prakash Sharma
 
// C++ implementation of the above approach
#include 
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, ZeroesInWindow=0;
 
    // find the sum and product of first K digits
    for (int i = 0; i < m; i++) {
        sum += (str[i] - '0');
       
        if(str[i]!='0')
        product *= (str[i] - '0');
        else
        ZeroesInWindow++;
    }
 
    // Update maxProd and maxSum
    int maxProd = 0;
    if(ZeroesInWindow==0)
      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
        if(str[i]!='0' && str[i-m]!='0')
        product = product * (str[i] - '0') / ((str[i - m]) - '0');
        else if(str[i]!='0' && str[i-m]=='0')
        { 
           product = product * (str[i] - '0');
           ZeroesInWindow--;
        }
        else if(str[i]=='0' && str[i-m]!='0')
        {
           product = product / (str[i-m] - '0');
           ZeroesInWindow++;
        }
       
        // Update maxProd
        if(ZeroesInWindow==0)
        maxProd = max(maxProd, product);
 
        // Add the current digit and subtract
        // the first digit of previous window
        sum = sum + (str[i] - '0') - ((str[i - m]) - '0');
 
        // Update maxSum
        maxSum = max(maxSum, sum);
    }
 
    cout << "Maximum Product = " << maxProd;
    cout << "\nMaximum Sum = " << maxSum;
}
 
// Driver code
int main()
{
    string str = "3601990545";
    int m = 3;
 
    maxProductSum(str, m);
}


Java
// Code Improved By Surya Prakash Sharma
 
// Java implementation 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, ZeroesInWindow=0;
 
    // find the sum and product of first K digits
    for (int i = 0; i < m; i++)
    {
        sum += (str.charAt(i) - '0');
       
        if(str.charAt(i)!='0')
        product *= (str.charAt(i) - '0');
        else
        ZeroesInWindow++;
         
    }
 
    // Update maxProd and maxSum
    int maxProd = 0;
    if(ZeroesInWindow==0)
      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
        if(str.charAt(i)!='0' && str.charAt(i-m)!='0')
        product = product * (str.charAt(i) - '0') / ((str.charAt(i-m)) - '0');
        else if(str.charAt(i)!='0' && str.charAt(i-m)=='0')
        { 
           product = product * (str.charAt(i) - '0');
           ZeroesInWindow--;
        }
        else if(str.charAt(i)=='0' && str.charAt(i-m)!='0')
        {
           product = product / (str.charAt(i-m) - '0');
           ZeroesInWindow++;
        }
       
        // Update maxProd
        if(ZeroesInWindow==0)
        maxProd = Math.max(maxProd, product);
 
        // Add the current digit and subtract
        // the first digit of previous window
        sum = sum + (str.charAt(i) - '0') - ((str.charAt(i-m)) - '0');
 
        // Update maxSum
        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 = "3601990545";
        int m = 3;
        maxProductSum(str, m);
    }
}
 
// This code is contributed
// by ajit


Python 3
# Python 3 implementation 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


C#
// C# implementation 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


PHP


Javascript


输出
Maximum Product = 126
Maximum Sum = 18

有效的方法:这个想法是使用滑动窗口的概念。首先找到M个连续数字的和和乘积,并更新maxProd和maxSum。
然后从第 M 个索引开始遍历并将当前数字添加到总和中并从总和中减去 str[iM],即仅考虑 M 个元素/数字。对于产品也是如此。并不断更新 maxSum 和 maxProd。

C++

// Code Improved By Surya Prakash Sharma
 
// C++ implementation of the above approach
#include 
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, ZeroesInWindow=0;
 
    // find the sum and product of first K digits
    for (int i = 0; i < m; i++) {
        sum += (str[i] - '0');
       
        if(str[i]!='0')
        product *= (str[i] - '0');
        else
        ZeroesInWindow++;
    }
 
    // Update maxProd and maxSum
    int maxProd = 0;
    if(ZeroesInWindow==0)
      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
        if(str[i]!='0' && str[i-m]!='0')
        product = product * (str[i] - '0') / ((str[i - m]) - '0');
        else if(str[i]!='0' && str[i-m]=='0')
        { 
           product = product * (str[i] - '0');
           ZeroesInWindow--;
        }
        else if(str[i]=='0' && str[i-m]!='0')
        {
           product = product / (str[i-m] - '0');
           ZeroesInWindow++;
        }
       
        // Update maxProd
        if(ZeroesInWindow==0)
        maxProd = max(maxProd, product);
 
        // Add the current digit and subtract
        // the first digit of previous window
        sum = sum + (str[i] - '0') - ((str[i - m]) - '0');
 
        // Update maxSum
        maxSum = max(maxSum, sum);
    }
 
    cout << "Maximum Product = " << maxProd;
    cout << "\nMaximum Sum = " << maxSum;
}
 
// Driver code
int main()
{
    string str = "3601990545";
    int m = 3;
 
    maxProductSum(str, m);
}

Java

// Code Improved By Surya Prakash Sharma
 
// Java implementation 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, ZeroesInWindow=0;
 
    // find the sum and product of first K digits
    for (int i = 0; i < m; i++)
    {
        sum += (str.charAt(i) - '0');
       
        if(str.charAt(i)!='0')
        product *= (str.charAt(i) - '0');
        else
        ZeroesInWindow++;
         
    }
 
    // Update maxProd and maxSum
    int maxProd = 0;
    if(ZeroesInWindow==0)
      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
        if(str.charAt(i)!='0' && str.charAt(i-m)!='0')
        product = product * (str.charAt(i) - '0') / ((str.charAt(i-m)) - '0');
        else if(str.charAt(i)!='0' && str.charAt(i-m)=='0')
        { 
           product = product * (str.charAt(i) - '0');
           ZeroesInWindow--;
        }
        else if(str.charAt(i)=='0' && str.charAt(i-m)!='0')
        {
           product = product / (str.charAt(i-m) - '0');
           ZeroesInWindow++;
        }
       
        // Update maxProd
        if(ZeroesInWindow==0)
        maxProd = Math.max(maxProd, product);
 
        // Add the current digit and subtract
        // the first digit of previous window
        sum = sum + (str.charAt(i) - '0') - ((str.charAt(i-m)) - '0');
 
        // Update maxSum
        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 = "3601990545";
        int m = 3;
        maxProductSum(str, m);
    }
}
 
// This code is contributed
// by ajit

Python3

# Python 3 implementation 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

C#

// C# implementation 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

PHP


Javascript


输出
Maximum Product = 100
Maximum Sum = 19