Skip to content

Latest commit

 

History

History
35 lines (25 loc) · 1007 Bytes

152. Maximum Product Subarray.md

File metadata and controls

35 lines (25 loc) · 1007 Bytes

##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.
public int maxProduct(int[] nums) {
    	/* 注意负数的情况 {-3,1,-2} ; 重新开始{-3,-2, 0, -8, -2}
    	 * 需要五个变量:分别保存local 和overall 的负数最小值、正数最大值以及最终结果。
    	 * */
    	
    	if (nums.length == 0) return 0;
    	
    	int max = nums[0];
    	int min = nums[0];
    	int local_max = nums[0];
    	int local_min = nums[0];
    	int ans = nums[0]; 
    	
    	for (int i = 1; i < nums.length; i++){
    		local_max = max * nums[i];
    		local_min = min * nums[i];
    		
    		max = Math.max(Math.max(local_max, local_min), nums[i]);
    		min = Math.min(Math.min(local_max, local_min), nums[i]); 
    		ans = Math.max(ans, max);	
    	}
    	return ans;        
    }