Given an array that contains both positive and negative integers, find the product of the maximum product subarray.

0

Given an array that contains both positive and negative integers, find the product of the maximum product subarray.




Cpp Program Code:

Here's the C++ code to find the length of the longest valid parenthesis substring:



The maxProductSubarray function takes a vector of integers nums as input and returns the maximum product of any subarray of nums.


The function first initializes maxProduct, minProduct, and result to nums[0]. These variables keep track of the maximum product of any subarray ending at index i, the minimum product of any subarray ending at index i, and the maximum product of any subarray seen so far, respectively.


Then, the function loops through the elements of nums starting from index 1. If nums[i] is negative, the function swaps maxProduct and minProduct to handle negative numbers properly.


The function then updates maxProduct and minProduct by taking the maximum and minimum of nums[i] and the product of maxProduct and nums[i] or minProduct and nums[i], respectively.


Finally, the function updates result to be the maximum of result and maxProduct.


In the main function, we create two arrays arr1 and arr2, call maxProductSubarray on them, and print the results. The output should be 180 and 60, respectively.

Post a Comment

0Comments
Post a Comment (0)