Find the contiguous subarray within an array (containing at least one number) which has the largest sum. For example, given the array [−2,1,−3,4,−1,2,1,−5,4], the contiguous subarray [4,−1,2,1] has the largest sum = 6.
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.
Near Brute force
If we store result from i to j in t[i][j], the runtime is O(n^2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
publicintmaxProduct(int[] A){
int maxvalue=0;
for(int i=0;i<A.length;i++){
for(int j=i;j<A.length;j++){
int tmp=1;
for(int k=i;k<=j;k++){
tmp*=A[k];
}
if(tmp>maxvalue){
maxvalue=tmp;
}
}
}
return maxvalue;
}
DP? Solution
There are only two cases when we get a larger result
mininum(negative) value multiply cur value(which happens to be negative)
maximum value multiply cur value
Be careful with the special case when multiplying both would decrease the result, then change start point to self