For example, given the array [2,3,-2,4], the contiguous subarray [2,3] has the largest product = 6.
Solution:
Suppose there are no 0 in the array, then the answer of an array [0, ... ,n] must comes from [0, ..., i] or [i, ..., n].
Proof:
1. If there are no negative number or there are even negative number, the answer is [0,n];
2. If there are odd negative number, say m, then we can choose m-1 negative number. That is, the subarray always contains one end of the array.
Consider there might be 0 in the array, we just need to break the array and run the algorithm above;
Code:
int maxProduct(vector<int>& nums) {
int max = nums[0];
int product;
int begin = 0;
int i;
while( begin < nums.size() )
{
if( nums[begin] == 0 )
{
begin++;
continue;
}
product = nums[begin];
if( product > max ) max = product;
for( i = begin+1; i < nums.size() && nums[i] != 0; i++ )
{
product *= nums[i];
if( product > max ) max = product;
}
if( i < nums.size() && max < 0 ) max = 0;
while( begin < i-1 )
{
product /= nums[begin];
if( product > max ) max = product;
begin++;
}
begin = i+1;
}
return max;
}
runtime: 4ms
Solution 2:
DP, code:
int maxProduct(vector<int>& nums) {
if( nums.size() == 0 ) return 0;
int mmax;
int maxLocal, minLocal;
maxLocal = nums[0];
minLocal = nums[0];
mmax = nums[0];
for( int i = 1; i < nums.size(); i++ )
{
int preMaxLocal = maxLocal;
maxLocal = max( minLocal*nums[i], max( maxLocal*nums[i], nums[i] ) );
minLocal = min( preMaxLocal*nums[i], min( minLocal*nums[i], nums[i] ) );
mmax = max( mmax, maxLocal );
}
return mmax;
}
runtime: 8ms