Maximum Product Subarray

时间:2022-05-24 00:44:31

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]);

 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 == ) return ;
if (nums.length == ) return nums[]; int[] min = new int[nums.length];
int[] max = new int[nums.length]; min[] = nums[];
max[] = nums[]; for (int i = ; i < nums.length; i++) {
min[i] = min(nums[i], min[i - ] * nums[i], max[i - ] * nums[i]);
max[i] = max(nums[i], min[i - ] * nums[i], max[i - ] * nums[i]);
} int tempMax = max[];
for (int i = ; i < max.length; i++) {
if (tempMax < max[i]) {
tempMax = max[i];
}
}
return tempMax; } 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));
}
}

更简洁的做法:

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 == ) return ;
if (nums.length == ) return nums[]; int pre_temp_min = nums[];
int pre_temp_max = nums[];
int global_max = nums[]; for (int i = ; 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/