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.

Similar: 53. Maximum Subarray

198. House Robber

238. Product of Array Except Self

 

 1 public class Solution {
 2     public int maxProduct(int[] nums) {
 3         if (nums.length < 1) return 0;
 4         int max = nums[0];
 5         int maxPre = nums[0]; // the max product include current val
 6         int minPre = nums[0]; // the min product include current val
 7         for (int i = 1; i < nums.length; i++) {
 8             int tmp1 = maxPre * nums[i];
 9             int tmp2 = minPre * nums[i];
10             maxPre = Math.max(nums[i], Math.max(tmp1, tmp2));
11             minPre = Math.min(nums[i], Math.min(tmp1, tmp2));
12             max = max > maxPre ? max : maxPre;
13         }
14         return max;
15     }
16 }

 

posted @ 2016-04-17 06:49  Joyce-Lee  阅读(175)  评论(0编辑  收藏  举报