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
.
本题和求最大子数组和有点像,但不同的是两个负数相乘,所以记录当前最小数
1 public class Solution { 2 public int maxProduct(int[] nums) { 3 if (nums.length==0){ 4 return 0; 5 } 6 if (nums.length<2){ 7 return nums[0]; 8 } 9 int max=nums[0]; 10 int min=nums[0]; 11 int res=nums[0]; 12 for (int i=1;i<nums.length;i++){ 13 int temp1=max*nums[i]; 14 int temp2=min*nums[i]; 15 max=Math.max(nums[i],Math.max(temp1,temp2)); 16 min=Math.min(nums[i],Math.min(temp1,temp2)); 17 res=Math.max(res,max); 18 } 19 return res; 20 } 21 }
leetcode 152. Maximum Product Subarray
原文:http://www.cnblogs.com/sure0328/p/7126831.html