1. Title
Maximum Product Subarray
2. Http address
https://leetcode.com/problems/maximum-product-subarray/
3. The question
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
.
4 My code(AC)
-
1 // Accepted 2 public static int maxProductTwo(int[] nums) { 3 4 int res_opt = nums[0]; 5 int tmp = 0; 6 int max_bf,max_cur; 7 int min_bf,min_cur; 8 max_bf = nums[0]; 9 min_bf = nums[0]; 10 for(int i = 1; i < nums.length; i++){ 11 12 max_cur = Math.max(max_bf * nums[i], nums[i]); 13 max_cur = Math.max(min_bf * nums[i], max_cur); 14 min_cur = Math.min(max_bf * nums[i], nums[i]); 15 min_cur = Math.min(min_bf * nums[i], min_cur); 16 17 18 tmp = Math.max(min_bf*nums[i], max_bf*nums[i]); 19 res_opt = Math.max(res_opt, tmp); 20 res_opt = Math.max(res_opt, nums[i]); 21 22 max_bf = max_cur; 23 min_bf = min_cur; 24 } 25 26 return res_opt; 27 }