leetcode 152. Maximum Product Subarray
阿新 • • 發佈:2017-07-06
style 最小數 int least 求最大子數組 ast fin urn bsp
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 classSolution { 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