LeetCode-152 Maximum Product Subarray
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
.
思路:使用动态规划。
设max[i]是以num[i]为结尾元素的子数组的最大乘积;
设min[i]是以num[i]为结尾元素的子数组的最小乘积;
如果max[i] != 0 && min[i] != 0,则
max[i+1] = Math.max(max[i] * num[i+1], min[i]*num[i+1]); 递推式1
min[i+1] = Math.min(max[i] * num[i+1], min[i]*num[i+1]); 递推式2
如果max[i] == 0 || min[i] = 0;
max[i+1] = Math.max(num[i+1], Math.max(max[i] * num[i+1], min[i]*num[i+1])); 递推式3
min[i+1] = Math.min(num[i+1], Math.min(max[i] * num[i+1], min[i]*num[i+1])) ; 递推式4
两种情况用递推式3和递推式4就能统一处理。
代码如下:
public int maxProduct(int[] nums) { int max = nums[0]; int min = nums[0]; int result = nums[0]; for(int i=1; i<nums.length; i++) { int tmax = max; int tmin = min; max = Math.max(nums[i], Math.max(tmax*nums[i], tmin*nums[i])); min = Math.min(nums[i], Math.min(tmax*nums[i], tmin*nums[i])); if(max > result) result = max; } return result; }
posted on 2015-04-21 21:55 linxiong1991 阅读(98) 评论(0) 编辑 收藏 举报