{"id":2046,"date":"2024-03-09T13:00:00","date_gmt":"2024-03-09T13:00:00","guid":{"rendered":"https:\/\/favtutor.com\/articles\/?p=2046"},"modified":"2024-03-11T07:51:24","modified_gmt":"2024-03-11T07:51:24","slug":"maximum-product-subarray-problem","status":"publish","type":"post","link":"https:\/\/favtutor.com\/articles\/maximum-product-subarray-problem\/","title":{"rendered":"Find Maximum Product Subarray (C++, Java, Python)"},"content":{"rendered":"\n<p>A subarray is a continuous sequence of an array and a lot of algorithms like <a href=\"https:\/\/favtutor.com\/blogs\/kadanes-algorithm-python\">Kadane\u2019s algorithm<\/a>, <a href=\"https:\/\/favtutor.com\/blogs\/sliding-window-algorithm\">sliding window<\/a>, etc. help to determine the maximum sum of the subarray or to find the sum of the maximum k-length subarray, etc. In this article, we will discuss the Maximum product Subarray problem with implementation in C++, Java, and Python.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><strong>Maximum Product Subarray Problem<\/strong><\/h2>\n\n\n\n<p><strong>In the Maximum Product Subarray problem, we are given an array and we have to find a subarray such that the product of all the elements in that subarray will be the largest.<\/strong><\/p>\n\n\n\n<p>For example:\u00a0 <\/p>\n\n\n\n<p><strong>INPUT:<\/strong>\u00a0 -1, 2, 3, -2<\/p>\n\n\n\n<p class=\"has-text-align-left\"><strong>OUTPUT: <\/strong>\u00a0 12\u00a0 ( -1 * 2 * 3 * -2)\u00a0<\/p>\n\n\n\n<p><strong>INPUT:\u00a0 \u00a0<\/strong> \u00a0 1, 2, 3,- 2<\/p>\n\n\n\n<p><strong>OUTPUT<\/strong>: \u00a0 6\u00a0 ( 1 * 2 * 3)\u00a0<\/p>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter is-resized\"><img decoding=\"async\" src=\"https:\/\/lh7-us.googleusercontent.com\/zmxuPZ_VHOvfXelhF1bzqsMFI0zHdAQBIcLWOG48xB_cBaU1TITclL8aFWc44oWKDoN5rgZfXlyemzS9O-YAG0SFGw5ThP4iDbX2_k8960uteMptGOHYJh5hJmIuduApYkdHeLrNyqCv3NFOTh_B7o8\" alt=\"Example of Maximum Product Subarray problem\" style=\"width:1033px;height:auto\"\/><\/figure>\n<\/div>\n\n\n<p>The basic or naive approach is to find all the subarrays and then find which among them have the largest product. Let\u2019s see step by step solution.<\/p>\n\n\n\n<ol class=\"wp-block-list\">\n<li>Create a loop of size n<\/li>\n\n\n\n<li>Create another loop starting from the index of the previous loop.<\/li>\n\n\n\n<li>Now find the product of the given subarray and compare it with the max value.<\/li>\n\n\n\n<li>If it is greater than max variable update max to this new product.<\/li>\n\n\n\n<li>Return the max element.<\/li>\n<\/ol>\n\n\n\n<p>The time complexity for the above process is O(n*n). Where n is the size of the array. We are iterating two loops to generate all the subarrays. The space complexity for the above code is O(1) as we are not using any extra space.\u00a0<\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><strong>Optimized Approach for Maximum Product Subarray<\/strong><\/h2>\n\n\n\n<p>In the above approach, the time complexity is huge is can be reduced if we use the concept of Kadane\u2019s algorithm. In this, we will first traverse the array from the left side and find its maximum value then traverse the array from the right side and find its maximum value. Return the maximum value among both of them. <\/p>\n\n\n\n<p>We are doing this as we know if we have a negative value the maximum product either lies on the left side or right. But if we have two negative values, the product will be positive only.<\/p>\n\n\n\n<p>Let\u2019s understand this step by step:<\/p>\n\n\n\n<figure class=\"wp-block-image\"><img decoding=\"async\" src=\"https:\/\/lh7-us.googleusercontent.com\/cLGb0trdBJbCcWQPSVpeL7z1lkENTMiMMd0nTAiK139eNywSa3Uxu-BCLHEXusAUaifxLG9vNN1fpHJDEvVKamws24lkL_XWfNzHyjoayJNVqAC2wnpZQgev3J9ZBR_acUaleVgHJIB0nDqCuLmSv4w\" alt=\"Optimized approach\"\/><\/figure>\n\n\n\n<ul class=\"wp-block-list\">\n<li>First, create a variable large that stores the maximum value.<\/li>\n\n\n\n<li>Now create another variable curr that keeps track of the current product of the subarray. Iterate the loop from left to right and keep updating the curr value by multiplying the current value by curr.<\/li>\n<\/ul>\n\n\n\n<figure class=\"wp-block-image\"><img decoding=\"async\" src=\"https:\/\/lh7-us.googleusercontent.com\/HT4INKa_C3X7DeMH2gCpysV3d09Xv4SMCr6AcVb3q3wMwP5gqolG4hzV2o8LUXZX8J5Krny0m0h7MXPtH6LT2XavPcg3EwsEAyDtmzFKkk8F8kn8CeZXy4zgDdTk8anhWYfUtZMueR53bw4rd7Kwpy8\" alt=\"Array\"\/><\/figure>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Update the large to a maximum value of curr and mx.<\/li>\n\n\n\n<li>Repeat the above two steps from the right to the left side.<\/li>\n\n\n\n<li>Return the large value.<\/li>\n<\/ul>\n\n\n\n<figure class=\"wp-block-image\"><img decoding=\"async\" src=\"https:\/\/lh7-us.googleusercontent.com\/8LbxZAvmtPp82W11UtiHvZMBFvsLi4ICFYQure-2lWFzEZYJx5TbXvwUlKCzhbYVlIWSexwfX5nHXJ5bqlD6YhI2vte3kzvKlKb_V4vLWNuXQp2DN5Ogzx6pD3TR5eobdhrJbhzcKh3JhT-zQjlBY0M\" alt=\"Output\"\/><\/figure>\n\n\n\n<p>Let\u2019s Examine the code for the above process.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>C++ Code<\/strong><\/h3>\n\n\n\n<p>Below is the C++ program to find Maximum Product Subarray:<\/p>\n\n\n\n<div class=\"wp-block-codemirror-blocks-code-block code-block\"><pre class=\"CodeMirror\" data-setting=\"{&quot;mode&quot;:&quot;clike&quot;,&quot;mime&quot;:&quot;text\/x-c++src&quot;,&quot;theme&quot;:&quot;material&quot;,&quot;lineNumbers&quot;:true,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;language&quot;:&quot;C++&quot;,&quot;modeName&quot;:&quot;cpp&quot;}\">#include&lt;bits\/stdc++.h&gt;\nusing namespace std;\n\nint find_max(vector&lt;int&gt;&amp;arr){\n    int large = INT_MIN;\n    int curr = 1;\n\n    \/\/ left iteration\n    for(int i=0;i&lt;arr.size();i++){\n        curr = curr*arr[i];\n        large = max(large, curr);\n        if(curr==0) curr=1;\n    }\n\n    curr = 1;\n    \/\/ right iteration\n    for(int i=arr.size()-1;i&gt;=0;i--){\n        curr = curr*arr[i];\n        large = max(large, curr);\n        if(curr==0) curr=1;\n    }\n\n    \/\/ return the largest value\n    return large;\n}\n\nint main(){\n    vector&lt;int&gt;arr = {1, 0, -1, 2, 3};\n\n    int and  = find_max(arr);\n    cout&lt;&lt;&quot;maximum product of subarray is: &quot;&lt;&lt;ans&lt;&lt;endl;\n    return 0;\n}<\/pre><\/div>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>Java Code<\/strong><\/h3>\n\n\n\n<p>You can implement it in Java also:<\/p>\n\n\n\n<div class=\"wp-block-codemirror-blocks-code-block code-block\"><pre class=\"CodeMirror\" data-setting=\"{&quot;mode&quot;:&quot;clike&quot;,&quot;mime&quot;:&quot;text\/x-java&quot;,&quot;theme&quot;:&quot;material&quot;,&quot;lineNumbers&quot;:true,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;language&quot;:&quot;Java&quot;,&quot;modeName&quot;:&quot;java&quot;}\">import java.util.*;\n\nclass MaximumProductSubarray {\n    \n    static int findMax(ArrayList&lt;Integer&gt; arr) {\n        int large = Integer.MIN_VALUE;\n        int curr = 1;\n\n        \/\/ Left iteration\n        for (int i = 0; i &lt; arr.size(); i++) {\n            curr *= arr.get(i);\n            large = Math.max(large, curr);\n            if (curr == 0) curr = 1;\n        }\n\n        curr = 1;\n        \/\/ Right iteration\n        for (int i = arr.size() - 1; i &gt;= 0; i--) {\n            curr *= arr.get(i);\n            large = Math.max(large, curr);\n            if (curr == 0) curr = 1;\n        }\n\n        \/\/ Return the largest value\n        return large;\n    }\n\n    public static void main(String[] args) {\n        ArrayList&lt;Integer&gt; arr = new ArrayList&lt;&gt;(Arrays.asList(1, 0, -1, 2, 3));\n\n        int ans = findMax(arr);\n        System.out.println(&quot;Maximum product of subarray is: &quot; + ans);\n    }\n}<\/pre><\/div>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>Python Code<\/strong><\/h3>\n\n\n\n<p>Here is the Python program for the optimized approach:<\/p>\n\n\n\n<div class=\"wp-block-codemirror-blocks-code-block code-block\"><pre class=\"CodeMirror\" data-setting=\"{&quot;mode&quot;:&quot;python&quot;,&quot;mime&quot;:&quot;text\/x-python&quot;,&quot;theme&quot;:&quot;material&quot;,&quot;lineNumbers&quot;:true,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;language&quot;:&quot;Python&quot;,&quot;modeName&quot;:&quot;python&quot;}\">def find_max(arr):\n    large = float('-inf')\n    curr = 1\n\n    # Left iteration\n    for num in arr:\n        curr *= num\n        large = max(large, curr)\n        if curr == 0:\n            curr = 1\n\n    curr = 1\n    # Right iteration\n    for i in range(len(arr) - 1, -1, -1):\n        curr *= arr[i]\n        large = max(large, curr)\n        if curr == 0:\n            curr = 1\n\n    # Return the largest value\n    return large\n\nif __name__ == &quot;__main__&quot;:\n    arr = [1, 0, -1, 2, 3]\n\n    ans = find_max(arr)\n    print(&quot;Maximum product of subarray is:&quot;, ans)<\/pre><\/div>\n\n\n\n<p><strong>Output: <\/strong>&nbsp;<\/p>\n\n\n\n<pre class=\"wp-block-code has-black-color has-text-color has-background has-link-color wp-elements-c255bdd93535dba6fe0af93ae1954db5\" style=\"background-color:#fedcba\"><code>Maximum product of subarray is: 6<\/code><\/pre>\n\n\n\n<p>The time complexity for the above-optimized approach to finding the maximum product array is O(n) where n is the size of the array. As we are just iterating two loops whose total time complexity is 2*O(n) the overall time complexity becomes O(n). The space complexity will remain the same i.e. O(1).<\/p>\n\n\n\n<p>Here is a comparison of how much better is the optimized approach:<\/p>\n\n\n\n<figure class=\"wp-block-table\"><table><thead><tr><th class=\"has-text-align-center\" data-align=\"center\"> Approach<\/th><th class=\"has-text-align-center\" data-align=\"center\">Time Complexity<\/th><th class=\"has-text-align-center\" data-align=\"center\">Space Complexity<\/th><th>Description<\/th><\/tr><\/thead><tbody><tr><td class=\"has-text-align-center\" data-align=\"center\">Brute Force<\/td><td class=\"has-text-align-center\" data-align=\"center\">O(n*n)<\/td><td class=\"has-text-align-center\" data-align=\"center\">O(1)<\/td><td>We are finding all the subarrays of the given array which laid time complexity to O(n*n).<\/td><\/tr><tr><td class=\"has-text-align-center\" data-align=\"center\">Optimized Approach<\/td><td class=\"has-text-align-center\" data-align=\"center\">O(n)<\/td><td class=\"has-text-align-center\" data-align=\"center\">O(1)<\/td><td>We are just iterating the loop two times one to find value from left to right and another from right to left.<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<h2 class=\"wp-block-heading\"><strong>Conclusion<\/strong><\/h2>\n\n\n\n<p>In this article, we explore many ways to find the maximum product of the subarray, a famous <a href=\"https:\/\/leetcode.com\/problems\/maximum-product-subarray\/description\/\" target=\"_blank\" rel=\"noreferrer noopener nofollow\">leetcode problem<\/a>. Through careful analysis of all the approaches, we find the most efficient way to do it in O(n) time complexity. <\/p>\n","protected":false},"excerpt":{"rendered":"<p>Learn how to find the Maximum Product Subarray, a problem for leetcode, with implementation in C++, Java, and Python.<\/p>\n","protected":false},"author":14,"featured_media":2048,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"jnews-multi-image_gallery":[],"jnews_single_post":null,"jnews_primary_category":{"id":"","hide":""},"footnotes":""},"categories":[7],"tags":[14,15],"class_list":["post-2046","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-data-structures-algorithms","tag-dsa","tag-leetcode"],"_links":{"self":[{"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/posts\/2046","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/users\/14"}],"replies":[{"embeddable":true,"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/comments?post=2046"}],"version-history":[{"count":4,"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/posts\/2046\/revisions"}],"predecessor-version":[{"id":2306,"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/posts\/2046\/revisions\/2306"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/media\/2048"}],"wp:attachment":[{"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/media?parent=2046"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/categories?post=2046"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/tags?post=2046"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}