最大连续子数组乘积问题
问题描述
在一个整型数组中寻找连续的元素(至少包含1个元素)构成子数组使得其元素乘积最大。
例如:给定数组 {2,3,-2,4};
最大连续元素构成的子数组为 {2,3},最大乘积为 6。
问题分析
注意:数组元素可能为 负数、0、整数。 其次,元素要连续。
算法设计
package com.bean.algorithmbasic;
public class MaximumProductSubarray {
/*
* 最大连续子数组乘积
*
* 给定一个整形数组,求最大子数组的乘积。
*
* 问题分析:
* 数组元素可能包含正数、负数和0.
* 另外,根据题目要求,子数组要连续。
*
* */
public static int maxProduct(int[] A) {
//如果数组为null或者数组长度为0,直接返回0.
if (A == null || A.length == 0) {
return 0;
}
//开始将A[0]分别设置为:最大值、最小值,和最终的返回结果。
int max = A[0], min = A[0], result = A[0];
//从数组的第二个元素开始取值
for (int i = 1; i < A.length; i++) {
int temp = max;
//状态转换方程的定义和实现
max = Math.max(Math.max(max * A[i], min * A[i]), A[i]);
min = Math.min(Math.min(temp * A[i], min * A[i]), A[i]);
//始终用result存放最大值,以返回结果。
if (max > result) {
result = max;
}
}
return result;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
int[] arraydemo= {2,3,-2,4};
int RESULT=maxProduct(arraydemo);
System.out.println("RESULT IS: "+RESULT);
}
}
(完)