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; } }
运行结果:
相关文章推荐
- leetcode - Maximum Product Subarray
- *LeetCode-Maximum Product Subarray
- Maximum Product Subarray——LeetCode
- [LeetCode]Maximum Product Subarray
- [leetcode-152]Maximum Product Subarray(c)
- 【LeetCode-面试算法经典-Java实现】【152-Maximum Product Subarray(子数组的最大乘积)】
- LeetCode-Maximum Product Subarray
- [LeetCode] Maximum Product Subarray
- leetcode Maximum Product Subarray
- LeetCode 152 Maximum Product Subarray (思维)
- 50 leetcode - Maximum Product Subarray
- leetcode:Maximum Product Subarray
- Leetcode-"Maximum product subarray"
- [LeetCode]152 Maximum Product Subarray
- [C++]LeetCode: 96 Maximum Product Subarray(动态规划)
- LeetCode - 152 - Maximum Product Subarray
- leetcode 152 Maximum Product Subarray
- leetcode-152 Maximum Product Subarray
- LeetCode Maximum Product Subarray
- leetcode 152 —— Maximum Product Subarray