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.
问题解析:
给定数组,给出最大乘积的连续子数组。
Answer
Solution 1:
DP。
- 子数组问题很适合使用动态规划来求解,与和最大的连续子数组的思想是相同的。
- 动态规划问题最核心的思想是找到其状态转移方程。首先说明“和最大的连续子数组”:我们定义,
Fi
表示以
i
结尾的和最大的连续子数组,求
F0,..,Fn−1 的最大值。所以这里我们最主要的是处理数组的局部当前最大连续乘积,和全局最大连续乘积的关系。 - 转换为式子有:
Fi=Max(Fi−1+Ai,Ai);global=Max(Fi,global); - 与最大和连续子数组相似,最大乘积连续子数组具有相同的思想,只是需要考虑负数的情况,因为两个负数相乘时,最后得到正值。所以一方面我们在保存乘积最大的值的同时,也要保存最小值(乘负数就是最小),然后比较最小值乘当前值、最大值乘当前值、当前值三者之间的最大和最小值,最大值和全局值比较。
- 转换为式子有:
maxFi=Max(maxFi−1∗Ai,Ai,minFi−1∗Ai);minFi=Min(minFi−1∗Ai,Ai,maxFi−1∗Ai);global=Max(maxFi,global);
class Solution {
public int maxProduct(int[] nums) {
if (nums == null || nums.length == 0) return 0;
if (nums.length == 1) return nums[0];
int[] maxhere = new int[nums.length];
int[] minhere = new int[nums.length];
maxhere[0] = nums[0];
minhere[0] = nums[0];
int res = nums[0];
for (int i = 1; i < nums.length; i++){
maxhere[i] = Math.max(Math.max(maxhere[i-1]*nums[i], nums[i]), minhere[i-1]*nums[i]);
minhere[i] = Math.min(Math.min(minhere[i-1]*nums[i], nums[i]), maxhere[i-1]*nums[i]);
res = Math.max(res, maxhere[i]);
}
return res;
}
}
- 时间复杂度:O(n),空间复杂度:O(n)
Solution 2:
对Solution1的DP优化。
- 通过观察状态转移函数,我们可以看出,每次计算只是用到前一个
maxhere
和minhere
,所以这里可以对程序进行改进,每次对前一个maxhere
和minhere
做记录,这样就节省了空间的存储。 - 因为在我们的程序中,先计算
maxhere
,后计算minhere
,所以只有在计算minhere
时,当前的maxhere[i]
会覆盖之前的maxhere[i-1]
,所以我们在每次计算前,将前一个minhere
保存下来,以便后面计算使用。
class Solution {
public int maxProduct(int[] nums) {
if (nums == null || nums.length == 0) return 0;
if (nums.length == 1) return nums[0];
int maxhere = nums[0];
int minhere = nums[0];
int res = nums[0];
for (int i = 1; i < nums.length; i++){
int maxpre = maxhere;
maxhere = Math.max(Math.max(maxpre*nums[i], nums[i]), minhere*nums[i]);
minhere = Math.min(Math.min(minhere*nums[i], nums[i]), maxpre*nums[i]);
res = Math.max(res, maxhere);
}
return res;
}
}
- 时间复杂度:O(n),空间复杂度:O(1)