连续子序列最大累加和
// 求和最大的连续子数组,有可能不唯一,返回一个即可
//什么是字数组:子数组就是 一个连续的 可为一个,可为多个
解题思路:初始化两个存储最大值变量,开始进行for循环,如果第一个元素小于0,重新赋予给最大值,如果大于零则,则进行累加起来,最后进行两个存储最大值变量比较。
package _3多维数和矩阵;
// 求和最大的连续子数组,有可能不唯一,返回一个即可
//什么是字数组:子数组就是 一个连续的 可为一个,可为多个
public class d返回子数组的最大累加和 {
public static void main(String[] args) {
int arr[] = new int[] { 1, -2, 3, 5, -2, 6, -1 };
martix(arr);// 暴力破解
System.out.println("-----------");
martix1(arr);// 加起来等于负数抛弃法
}
private static void martix1(int[] arr) {// on级别 递推法
// TODO Auto-generated method stub
int strmax = arr[0]; //首个最大值根后面的比较
int max = strmax; //最大累加和
int left = 0, right = 0;
for (int j = 1; j < arr.length; j++) {
if (strmax >= 0) {
strmax += arr[j];// 左子表的最大和为正,继续后面累加
} else {
strmax = arr[j]; //指针往右移
left = j;
}
if (strmax > max) {
max = strmax;
right = j;
}
}
System.out.println(max + ",left=" + left + ",right:" + right);
}
private static void martix(int[] arr) {// on平方级别
// TODO Auto-generated method stub
int strmax1 = arr[0];
for (int i = 0; i < arr.length; i++) {// 这是头部循环
int max = arr[0];// 第一轮比较 以第一个 为开头
int strmax2 = max; 累加和缓存
for (int j = i + 1; j < arr.length; j++) {
max += arr[j];
if (max > strmax1) {// 如果第一个数 和第一个数和第二个数相加相比较
strmax2 = max;// 缓存区
}
}
if (strmax2 > strmax1) {
strmax1 = strmax2;
}
}
System.out.println(strmax1);
}
}