继续记录今天刷的一道简单的DP题目,题目意思很简单,如下:
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
.
public class Solution {
public int maxProduct(int[] A) {
int n = A.length;
int min = A[0], max = A[0], maxproduct = A[0];
for(int i = 1; i < n; i++){
if(A[i] >= 0){
max = A[i] > max*A[i] ? A[i] : max * A[i];
min = A[i] < min*A[i] ? A[i] : min * A[i];
}
else{
int temp = max;
max = A[i] > min*A[i] ? A[i] : min * A[i];
min = A[i] < temp*A[i] ? A[i] : temp * A[i];
}
maxproduct = max > maxproduct ? max : maxproduct;
}
return maxproduct;
}
}