clueless coding // TODO: be smarter

LeetCode Maximum Product Subarray: CPP Solution



TL;DR Code Solution


int maxProduct(vector<int>& nums) {
     if (nums.size() == 0) return 0;
int maxProduct = nums[0];
int minProduct = nums[0];
int maxRes = nums[0];
for (int i = 1; i < nums.size(); i++)
{
    if (nums[i] >= 0)
    {
        maxProduct = max(maxProduct * nums[i], nums[i]);
        minProduct = min(minProduct * nums[i], nums[i]);
    }
    else
    {
        int temp = maxProduct;
        maxProduct = max(minProduct * nums[i], nums[i]);
        minProduct = min(temp * nums[i],nums[i]);
    }
    maxRes = max(maxRes, maxProduct);
}
return maxRes;
}