Description:
Find the contiguous subarray within an array (containing at least one number) which has the largest product.
For example, given the array[2,3,-2,4],
The contiguous subarray[2,3]Has the largest Product =6
Idea: traverse the array from left to right, record the maximum and minimum values of the Child array product ending with the element currently traversed (because there may be negative numbers in the array ), at the same time, the maximum value of all obtained values is recorded. At the end of the loop, the maximum value of all obtained values is the expected value.
Code:
int Solution::maxProduct(int A[],int n){ if(n == 1) return A[0]; int max_temp = A[0]; int min_temp = A[0]; int result = A[0]; int i; for(i = 1;i < n;i++) { int max_temp2 = max_temp * A[i]; int min_temp2 = min_temp * A[i]; max_temp = max(max_temp2,max(min_temp2,A[i])); min_temp = min(min_temp2,min(max_temp2,A[i])); if(max_temp > result) result = max_temp; } return result;}
Leetcode: Maximum Product subarray