class MaxSubSumProduct {
public static void main(String[] args) {
int[] a={1,-3,5,0,-4,3,-2,4,-1};
System.out.println("Maximum subsection sum: "+maxSubSum(a));
System.out.println("Maximum subsection product: "+maxSubProduct(a));
}
//最大子段和
public static int maxSubSum(int[] a){
int curSum=0; //当前和
int maxSum=0; //最大和
for(int i=0;i<a.length;i++){
curSum+=a[i];
if(curSum>maxSum){ //当前和大于最大和,交换
maxSum=curSum;
}else if(curSum<=0){ //当前和小于0,重置
curSum=0;
}
}
return maxSum;
}
//最大子段积
public static int maxSubProduct(int[] a){
int[] ma=new int[a.length]; //最大积数组
int[] mi=new int[a.length]; //最小积数组
ma[0]=a[0];
mi[0]=a[0];
int maxSubPro=0; //最大积
for(int i=1;i<a.length;i++){
//考虑到负负得正,数组元素值为0的影响,
//从 最大积前值*当前元素,最小积前值*当前元素,当前元素
//三者里面取最大(小)值
ma[i]=Math.max(Math.max(ma[i-1]*a[i],mi[i-1]*a[i]),a[i]);
mi[i]=Math.min(Math.min(ma[i-1]*a[i],mi[i-1]*a[i]),a[i]);
if(maxSubPro<ma[i]){
maxSubPro=ma[i];
}
}
return maxSubPro;
}
}
Java_最大子段和&最大子段积
最新推荐文章于 2022-05-17 20:43:46 发布
![](https://img-home.csdnimg.cn/images/20240711042549.png)