Maximum Product Subarray
Posted 北叶青藤
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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
.
分析:
因为这题要求乘积最大,而负数和负数相乘可是是正数,所以,我们必须得保存两个变量,即当到达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 }
更简洁的做法:
public class Solution { /** * @param nums: an array of integers * @return: an integer * cnblogs.com/beiyeqingteng/ */ public int maxProduct(int[] nums) { if (nums == null || nums.length == 0) return 0; if (nums.length == 1) return nums[0]; int pre_temp_min = nums[0]; int pre_temp_max = nums[0]; int global_max = nums[0]; for (int i = 1; i < nums.length; i++) { int temp_min = min(nums[i], pre_temp_min * nums[i], pre_temp_max * nums[i]); int temp_max = max(nums[i], pre_temp_min * nums[i], pre_temp_max * nums[i]); pre_temp_min = temp_min; pre_temp_max = temp_max; global_max = Math.max(global_max, temp_max); } return global_max; } public int max(int a, int b, int c) { return Math.max(a, Math.max(b, c)); } public int min(int a, int b, int c) { return Math.min(a, Math.min(b, c)); } }
转载请注明出处:cnblogs.com/beiyeqingteng/
以上是关于Maximum Product Subarray的主要内容,如果未能解决你的问题,请参考以下文章