Find the Substring with maximum product - GeeksforGeeks

18 Nov, 2021
Given string str containing only lowercase English alphabets of size N, the task is to find the substring having the maximum product.  
Each English alphabet has a value such that val(‘a’) = 0, val(‘b’) = 1, val(‘c’) = 2, ......, val(‘z’) = 25.
Examples:  
Input: str = “sdtfakdhdahdzz” Output: hdzz Here, the maximum product is for the substring “hdzz”. product = 7 * 3 * 25 * 25 = 13125Input: str = “geeksforgeeks” Output: geeksforgeeks  
 
Approach:  
First, traverse through the given string while maintaining a maximum product value.
Product will always keep increasing or will remain constant unless we encounter an ‘a’. Hence, start a new substring after each ‘a’ occurrence.
Also, along with the maximum product value, we will also maintain the substring to which the maximum product corresponds.
Once the entire string has been traversed, print the substring corresponding to the maximum product.
Below is the implementation of the above approach:  
C++
Java
Python3
C#
Javascript
// C++ program to find the maximum product substring #include <bits/stdc++.h>using namespace std; // Function to return the value of a characterint value(char x){    return (int)(x - 'a');} // Function to find the maximum product substringstring maximumProduct(string str, int n){    // To store substrings    string answer = "", curr = "";    long long maxProduct = 0, product = 1;     for (int i = 0; i < n; i++) {        product *= 1LL * value(str[i]);         curr += str[i];         // Check if current product is maximum        // possible or not        if (product >= maxProduct) {            maxProduct = product;            answer = curr;        }         // If product is 0        if (product == 0) {            product = 1;            curr = "";        }    }     // Return the substring with maximum product    return answer;} // Driver codeint main(){    string str = "sdtfakdhdahdzz";     int n = str.size();     // Function call    cout << maximumProduct(str, n) << endl;     return 0;}
// Java program to find the maximum product subString class GFG{  // Function to return the value of a characterstatic int value(char x){    return (int)(x - 'a');}  // Function to find the maximum product subStringstatic String maximumProduct(String str, int n){    // To store subStrings    String answer = "", curr = "";    long maxProduct = 0, product = 1;      for (int i = 0; i < n; i++) {        product *= 1L * value(str.charAt(i));          curr += str.charAt(i);          // Check if current product is maximum        // possible or not        if (product >= maxProduct) {            maxProduct = product;            answer = curr;        }          // If product is 0        if (product == 0) {            product = 1;            curr = "";        }    }      // Return the subString with maximum product    return answer;}  // Driver codepublic static void main(String[] args){    String str = "sdtfakdhdahdzz";      int n = str.length();      // Function call    System.out.print(maximumProduct(str, n) +"\n");  }} // This code is contributed by 29AjayKumar
# Python3 program to find the maximum product sub # Function to return the value of a characterdef value(x):    return (ord(x) - ord('a')) # Function to find the maximum product subdef maximumProduct(strr, n):     # To store subs    answer = ""    curr = ""    maxProduct = 0    product = 1     for i in range(n):        product *=value(strr[i])         curr += strr[i]         # Check if current product is maximum        # possible or not        if (product >= maxProduct):            maxProduct = product            answer = curr         # If product is 0        if (product == 0):            product = 1            curr = ""     # Return the sub with maximum product    return answer # Driver codeif __name__ == '__main__':    strr = "sdtfakdhdahdzz"     n = len(strr)     # Function call    print(maximumProduct(strr, n)) # This code is contributed by mohit kumar 29
// C# program to find the maximum product subString using System; public class GFG{ // Function to return the value of a characterstatic int value(char x){    return (int)(x - 'a');} // Function to find the maximum product subStringstatic String maximumProduct(String str, int n){    // To store subStrings    String answer = "", curr = "";    long maxProduct = 0, product = 1;     for (int i = 0; i < n; i++) {        product *= 1L * value(str[i]);         curr += str[i];         // Check if current product is maximum        // possible or not        if (product >= maxProduct) {            maxProduct = product;            answer = curr;        }         // If product is 0        if (product == 0) {            product = 1;            curr = "";        }    }     // Return the subString with maximum product    return answer;} // Driver codepublic static void Main(String[] args){    String str = "sdtfakdhdahdzz";     int n = str.Length;     // Function call    Console.Write(maximumProduct(str, n) +"\n"); }}// This code is contributed by PrinciRaj1992
<script>// Javascript program to find the// maximum product subString // Function to return the value of a characterfunction value(x){    return (x.charCodeAt() - 'a'.charCodeAt());}    // Function to find the maximum product subStringfunction maximumProduct(str, n){    // To store subStrings    let answer = "", curr = "";    let maxProduct = 0, product = 1;        for (let i = 0; i < n; i++) {        product *= (1 * value(str[i]));            curr += str[i];            // Check if current product is maximum        // possible or not        if (product >= maxProduct) {            maxProduct = product;            answer = curr;        }            // If product is 0        if (product == 0) {            product = 1;            curr = "";        }    }        // Return the subString with maximum product    return answer;}     // Driver Code      let str = "sdtfakdhdahdzz";        let n = str.length;        // Function call    document.write(maximumProduct(str, n) +"<br/>");     </script>
hdzz
 
Time Complexity: O(N)
Auxiliary Space: O(1)
mohit kumar 29
29AjayKumar
princiraj1992
susmitakundugoaldanga
rishavmahato348
ASCII
Mathematical
Strings
Strings
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Algorithm to solve Rubik's Cube
Program to print prime numbers from 1 to N.
Fizz Buzz Implementation
Program to multiply two matrices
Modular multiplicative inverse
Write a program to reverse an array or string
Reverse a string in Java
Longest Common Subsequence | DP-4
Check for Balanced Brackets in an expression (well-formedness) using Stack
Python program to check if a string is palindrome or not