您的位置:首页 > 其它

Leetcode:Maximum Product Subarray

2017-04-05 23:25 337 查看

连接:https://leetcode.com/problems/maximum-product-subarray/#/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.

思路:

整体的思路就是动态规划,left[i]为从开始到i的位置乘积数值,right[i]表示从结尾到i的位置乘积数值。最终的结果是:

max = Max{left[i],right[i],left[i]*right[i+1]};

其中值得注意的问题是:

left[i]如果为负数,且{i+1,…,size-1}的位置没有负数,则后面的数字相乘并不会把结果变成正数,所以此时需要把left[i]的值变成1.所以我们用leftNge[i]存储从开始位置到i位置有多少个负数。

nums[]中可能会出现0的数值,例如nums[i]==0,则left[i]=nums[i]*left[i-1]; left[i]==0,之后的如何left[i…size]恒等于0,所以若出现0的情况,则直接将left[i]=nums[i];rigth[]和rightNge[]的表示从结尾到位置i,原理基本一样。

代码如下:

public class Solution {

public int maxProduct(int[] nums) {
int max = nums[0];
int size = nums.length;
int[] left = new int[size];
int[] leftNge = new int[size];

int[] right = new int[size];
int[] rightNge = new int[size];
left[0] = nums[0];
right[size-1] = nums[size-1];
if(nums[0]<0)
leftNge[0]=1;
if(nums[size-1]<0){
rightNge[size-1]=1;
}
for(int i=1;i<size;i++){
if(nums[i]<0)
leftNge[i]=leftNge[i-1]+1;
else
leftNge[i]=leftNge[i-1];
}
for(int i=size-2;i>=0;i--){
if(nums[i]<0)
rightNge[i]=rightNge[i+1]+1;
else
rightNge[i]=rightNge[i+1];
}
for(int i=1;i<size-1;i++){
if(left[i-1]==0){
left[i] = nums[i];
}else{
left[i]=nums[i]*left[i-1];
if(left[i]<0&&rightNge[i+1]==0){
left[i]=1;
}
}
}

for(int i=size-2;i>=1;i--){
if(right[i+1]==0){
right[i] = nums[i];
}else{
right[i]=nums[i]*right[i+1];
if(right[i]<0&&left[i-1]==0)
right[i] = 1;
}
}
for(int i=0;i<size-1;i++){
int temp = left[i]*right[i+1];
max = Math.max(temp,max);
max = Math.max(left[i],max);
max = Math.max(right[i+1],max);
}
return max;
}
}


运行结果:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: