1. 子数组的最大和
输入一个整形数组,数组里有正数也有负数。数组中连续的一个或多个整数组成一个子数组,每个子数组都有一个和。求所有子数组的和的最大值。例如数组:arr[]={1, 2, 3, -2, 4, -3 } 最大子数组为 {1, 2, 3, -2, 4} 和为8。
解法1(时间复杂度O(N * N)空间复杂度O(1))
求出所有的子数组的和,比较选择出最大值。利用双重循环就可以遍历到所有的子数组。
public static void maxSum1(intarr[]) {int max=0,sum;for(int i=0;i
{
sum=0;for(int j=i;j
{//遍历数组的所有子数组,并将子数组的最大和保存在max中。
sum+=arr[j];
max=Math.max(max, sum);//max保存最大的子数组的和
}
}
System.out.println(max);
}
解法2(动态规划时间复杂度O(N)空间复杂度O(1))
遍历数组,用 sum 保存子数组的和,当 sum<0 时 将 arr[i] 赋值给 sum,用 max 保存最大值。
public static void maxSum(intarr[]){int max=0,sum=0;for(int i=0;i
{if(sum<=0){
sum=arr[i];//如果 sum<0 重新赋值
}else{
sum+=arr[i];
}
max=Math.max(sum, max);//将最大值保存在max中。
}
System.out.println(max);
}
2. 子数组的最大乘积
输入一个整形数组,数组里有正数也有负数。数组中连续的一个或多个整数组成一个子数组,每个子数组都有一个和。求所有子数组的和的最大值。例如数组:arr[]={1, 2, 3, -2, 4, 3 } 最大子数组为 {4,3} 积为12。
解法1(时间复杂度O(N * N)空间复杂度 O(1))
跟上面求最大子数组的和类似,利用双重循环遍历所有的子数组,求出所有子数组中值最大的。
public static void maxproduct(intarr[]){if(arr==null||arr.length==0)return;//如果数组为 null 或者长度为0直接返回
int max=0,product=1;//max保存子数组的最大乘积,product 用来保存每一个子数组的积
for(int i=0;i
product=1;for(int j=i;j
product*=arr[j];
max=Math.max(product, max);//max保存最大的子数组乘积
if(product==0)break;//如果当前子数组的乘积为0则以当前数组为头的后序数组的积全为0不用求。
}
}
System.out.println(max);
}
解法2(动态规划 时间复杂度O(N )空间复杂度 O(1))
跟上面求最大子数组的和类似,利用双重循环遍历所有的子数组,求出所有子数组中值最大的。以arr[i] 结尾的最大值可能由前面的以arr[i-1]结尾的 最大 负值,最大正数,和arr[i] 产生。例如数组:{2,-3,-4}以-4结尾的最大值,就是3*2=-6,与-4 相乘产生的。
public static void maxSubProduct(intarr[]){if(arr==null||arr.length==0)return;int max=arr[0],min=arr[0],maxend,result=0;for(int i=1;i
maxend=Max(max*arr[i],min*arr[i],arr[i]);//maxend 保存最大值
min=Min(max*arr[i], min*arr[i], arr[i]);//用于保存最小的负值,为下一个最大值最准备
max=maxend;
result=Math.max(result, max);
}
System.out.println(result);
}public static int Max(int a,int b,intc)
{//返回 a b c 中的最大值
a=Math.max(a, b);
a=Math.max(a, c);returna;
}public static int Min(int a,int b,intc)
{//返回 a b c 中的最小值
a=Math.min(a, b);
a=Math.min(a, c);returna;
}https://blog.csdn.net/u013309870/article/details/70144135