题目:
152. 乘积最大子数组
题解:
1. 题解一:双向遍历
public int maxProduct(int[] nums) {
if (nums.length == 0) {
return 0;
}
if (nums.length == 1) {
return nums[0];
}
int max_even = 1;
boolean flag = false;
boolean update = false;
int max = 0;
int max_odd = 1;
for (int i = 0; i < nums.length; i++) {
max_even *= nums[i];
max = Math.max(max, max_even);
if (nums[i] == 0) {
if (update) {
max = Math.max(max, max_odd);
}
max_even = 1;
max_odd = 1;
flag = false;
update = false;
continue;
}
if (flag) {
max_odd *= nums[i];
update = true;
continue;
}
if (nums[i] < 0) {
flag = true;
}
}
if (update) {
max = Math.max(max, max_odd);
}
flag = false;
update = false;
max_odd = 1;
for (int i = nums.length - 1; i >= 0; i--) {
if (nums[i] == 0) {
if (update) {
max = Math.max(max, max_odd);
}
max_odd = 1;
flag = false;
update = false;
continue;
}
if (flag) {
max_odd *= nums[i];
update = true;
continue;
}
if (nums[i] < 0) {
flag = true;
}
}
if (update) {
max = Math.max(max, max_odd);
}
return max;
}
public int maxProduct(int[] nums) {
if (nums.length == 0) {
return 0;
}
int max = 1;
int res = nums[0];
for (int i = 0; i < nums.length; i++) {
max *= nums[i];
res = Math.max(res, max);
}
max = 1;
for (int i = nums.length - 1; i >= 0; i--) {
max *= nums[i];
res = Math.max(res, max);
}
return res;
}
2. 题解二:动态规划
代码:
1. 代码一:双向遍历
public class code152 {
public static int maxProduct(int[] nums) {
if(nums.length == 0)
{
return 0;
}
int max = 1;
int res = nums[0];
for(int i = 0; i < nums.length; i++)
{
max *= nums[i];
if(max > res)
{
res = max;
}
if(nums[i] == 0)
{
max = 1;
}
}
max = 1;
for(int i = nums.length - 1; i >= 0; i--)
{
max *= nums[i];
if(max > res)
{
res = max;
}
if(nums[i] == 0)
{
max = 1;
}
}
return res;
}
public static void main(String[] args) {
int nums[] = { 2, 3, -2, 4 };
int res = maxProduct(nums);
System.out.println(res);
}
}
2. 代码二:动态规划
public class code152 {
public static int maxProduct(int[] nums) {
int n = nums.length;
if(n == 0)
{
return 0;
}
int dpMax[] = new int[n];
dpMax[0] = nums[0];
int dpMin[] = new int[n];
dpMin[0] = nums[0];
int max = nums[0];
for(int i = 1; i < n; i++)
{
dpMax[i] = Math.max(dpMin[i - 1] * nums[i], Math.max(dpMax[i - 1] * nums[i], nums[i]));
dpMin[i] = Math.min(dpMin[i - 1] * nums[i], Math.min(dpMax[i - 1] * nums[i], nums[i]));
max = Math.max(max, dpMax[i]);
}
return max;
}
public static void main(String[] args) {
int nums[] = { 2, 3, -2, 4 };
int res = maxProduct(nums);
System.out.println(res);
}
}
参考:
- 详细通俗的思路分析,多解法
- 子串问题用 DP
- 乘积最大子数组
- 画解算法:152. 乘积最大子序列
- 动态规划(理解无后效性)
- DP方法详解
- 多种思路求解
- 如何将思路一步步过渡到动态规划