标签:
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
.
分析:
因为这题要求乘积最大,而负数和负数相乘可是是正数,所以,我们必须得保存两个变量,即当到达A[i]时,前一个数A[i - 1]所对应的最大值和最小值max[i - 1] 和 min[i - 1]. max[i] 和min[i]和这些值有如下关系:
min[i] = min(nums[i], min[i - 1] * nums[i], max[i - 1] * nums[i]);
max[i] = max(nums[i], min[i - 1] * nums[i], max[i - 1] * nums[i]);
1 public class Solution { 2 /** 3 * @param nums: an array of integers 4 * @return: an integer 5 * cnblogs.com/beiyeqingteng/ 6 */ 7 public int maxProduct(int[] nums) { 8 if (nums == null || nums.length == 0) return 0; 9 if (nums.length == 1) return nums[0]; 10 11 int[] min = new int[nums.length]; 12 int[] max = new int[nums.length]; 13 14 min[0] = nums[0]; 15 max[0] = nums[0]; 16 17 for (int i = 1; i < nums.length; i++) { 18 min[i] = min(nums[i], min[i - 1] * nums[i], max[i - 1] * nums[i]); 19 max[i] = max(nums[i], min[i - 1] * nums[i], max[i - 1] * nums[i]); 20 } 21 22 int tempMax = max[0]; 23 for (int i = 1; i < max.length; i++) { 24 if (tempMax < max[i]) { 25 tempMax = max[i]; 26 } 27 } 28 return tempMax; 29 30 } 31 32 public int max(int a, int b, int c) { 33 return Math.max(a, Math.max(b, c)); 34 } 35 36 public int min(int a, int b, int c) { 37 return Math.min(a, Math.min(b, c)); 38 } 39 }
转载请注明出处:cnblogs.com/beiyeqingteng/
标签:
原文地址:http://www.cnblogs.com/beiyeqingteng/p/5631740.html