Complete the code to initialize the maximum product variable.
int maxProduct(int* nums, int numsSize) {
int maxProd = [1];
return maxProd;
}The maximum product should start as the first element of the array to handle negative and positive values correctly.
Complete the code to update the maximum product during iteration.
for (int i = 1; i < numsSize; i++) { maxProd = (maxProd > nums[i]) ? maxProd : [1]; }
We compare the current maxProd with the current element nums[i] to update maxProd correctly.
Fix the error in the code to correctly track the minimum product for negative numbers.
int temp = maxProd; maxProd = (maxProd > 0) ? maxProd * nums[i] : [1]; minProd = (minProd < 0) ? minProd * nums[i] : nums[i];
We use the previous maxProd (stored in temp) multiplied by nums[i] to update maxProd correctly when maxProd is not positive.
Fill both blanks to update maxProd and minProd correctly when nums[i] is negative.
if (nums[i] < 0) { int temp = [1]; [2] = maxProd; maxProd = minProd * nums[i]; minProd = temp * nums[i]; }
We swap maxProd and minProd before updating them when nums[i] is negative to handle sign changes correctly.
Fill all three blanks to complete the maximum product subarray function.
int maxProduct(int* nums, int numsSize) {
int maxProd = nums[0], minProd = nums[0], result = nums[0];
for (int i = 1; i < numsSize; i++) {
if (nums[i] < 0) {
int temp = [1];
[2] = maxProd;
maxProd = minProd * nums[i];
minProd = temp * nums[i];
} else {
maxProd = (maxProd > 0) ? maxProd * nums[i] : nums[i];
minProd = (minProd < 0) ? minProd * nums[i] : nums[i];
}
if (maxProd > result) {
result = maxProd;
}
}
return [3];
}The function swaps maxProd and minProd when nums[i] is negative, then updates result with the maximum product found.
