lintcode-medium-Maximum Product Subarray
Find the contiguous subarray within an array (containing at least one number) which has the largest product.
Example
For example, given the array [2,3,-2,4]
, the contiguous subarray [2,3]
has the largest product = 6
.
public class Solution { /** * @param nums: an array of integers * @return: an integer */ public int maxProduct(int[] nums) { // write your code here if(nums == null || nums.length == 0) return 0; int size = nums.length; int[] max = new int[size]; int[] min = new int[size]; int result = nums[0]; max[0] = nums[0]; min[0] = nums[0]; for(int i = 1; i < size; i++){ max[i] = Math.max(Math.max(min[i - 1] * nums[i], nums[i]), max[i - 1] * nums[i]); min[i] = Math.min(Math.min(max[i - 1] * nums[i], nums[i]), min[i - 1] * nums[i]); result = Math.max(result, max[i]); } return result; } }