题目:
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
.
代码:
1 public class Solution { 2 public int maxProduct(int[] nums) 3 { 4 int max=nums[0]; 5 int min=nums[0]; 6 int maxAns=nums[0]; 7 8 for(int i=1;i<nums.length;i++) 9 { 10 int mx=max; 11 int mn=min; 12 max=Math.max(Math.max(nums[i],mx*nums[i]),mn*nums[i]); 13 min=Math.min(Math.min(nums[i],mx*nums[i]),mn*nums[i]); 14 maxAns=Math.max(max,maxAns); 15 } 16 17 return maxAns; 18 } 19 }
注意红色部分,变量maxAns的存在很重要。
原文:http://www.cnblogs.com/hygeia/p/4643977.html