This is similar to the maximum sum subarray problem. The basic idea for that problem is to keep a best sum so far, and iterate through the array. Each number we either add it to the sum so far, or we start over with the number as the new sum so far. At the end we can return the largest running sum we saw while iterating through the array.
The multiplication problem has the same general idea. The catch is dealing with negative numbers; we have to catch the case of two negative numbers multiplying together into a positive. Therefore we keep two running products while iterating through the array; one for the most negative product and one for the most positive product. The rest of the problem is the same as the maximum sum solution.
int maxProduct(int* nums, int numsSize) {
int bestProduct;
int prevPosProduct, prevNegProduct;
bestProduct = nums[0];
prevPosProduct = nums[0];
prevNegProduct = nums[0];
for (int i = 1; i < numsSize; i++) {
int currentValue = nums[i];
int continuedProduct, continuedNegProduct;
if (currentValue > 0) {
continuedProduct = currentValue * prevPosProduct;
continuedNegProduct = currentValue * prevNegProduct;
} else {
continuedProduct = currentValue * prevNegProduct;
continuedNegProduct = currentValue * prevPosProduct;
}
if (continuedProduct > currentValue) {
prevPosProduct = continuedProduct;
} else {
prevPosProduct = currentValue;
}
if (continuedNegProduct < currentValue) {
prevNegProduct = continuedNegProduct;
} else {
prevNegProduct = currentValue;
}
if (prevPosProduct > bestProduct) {
bestProduct = prevPosProduct;
}
}
return bestProduct;