Maximum Product Subarray
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.
思路:利用动态规划思想,记录到每个数截止时的最大值和最小值,用来推导下一个数的最大值和最小值;
代码:
- int maxProduct(int A[], int n) {
- if(n==0) return 0;
- if(n==1) return A[0];
- int max_here_val = A[0];
- int min_here_val = A[0];
- int max_val = A[0];
- for(int i=1;i<n;i++) {
- int tmp = max_here_val;
- max_here_val = max(max(max_here_val * A[i],A[i]),min_here_val * A[i]); // the max value of current
- min_here_val = min(min(A[i],tmp * A[i]),min_here_val * A[i]); //the min value of current
- if(max_here_val > max_val) {
- max_val = max_here_val;
- }
- }
- return max_val;
- }

浙公网安备 33010602011771号