151 DSA Problem journey

151 DSA Problem journey

Maximum Product of subarray

Q4:)Given an integer array, find a subarray that has the largest product, and return the product.

The test cases are generated so that the answer will fit in a 32-bit integer.

Example :

Input: nums = [2,3,-2,4]
Output: 6
Explanation: [2,3] has the largest product 6.

Solution:
class Solution {
public:
    int maxProduct(vector<int>& nums) {
        int ct=1;
        int mt=INT_MIN;
        for(int i=0;i<nums.size();i++){
           ct=ct*nums[i];
           mt=max(ct,mt);
           if(ct==0)
           ct=1;
        }
        ct=1;
        for(int i=nums.size()-1;i>=0;i--){
            ct=ct*nums[i];
            mt=max(ct,mt);
            if(ct==0)
            ct=1;
        }
        return mt;         
    }
};

Explantion:
.)Initialize two variables: ct to 1 (current product) and mt to INT_MIN (maximum product).
.)Iterate through the elements of the nums vector from left to right.
   >Update ct by multiplying it with the current element.
   >Update mt to the maximum value between the current product (ct) and the maximum product encountered so far (mt).
   >If the current product becomes zero, reset ct to 1 to start calculating a new product.
.)Reset ct to 1.
.)Iterate through the elements of the nums vector from right to left.
   >Update ct by multiplying it with the current element.
   >Update mt to the maximum value between the current product (ct) and the maximum product encountered so far (mt).
   >If the current product becomes zero, reset ct to 1 to start calculating a new product.
.)Return the final maximum product (mt).

>This code efficiently calculates the maximum product of subarrays in the given vector. 
If a subarray has a zero, the code starts calculating a new product from the next element.

If anyone have better solution so please comment:)

Did you find this article valuable?

Support Gaurav Coding Blogs by becoming a sponsor. Any amount is appreciated!