整形数组最大子数组的和
要求求出整型数组的最大子数组的和,要求复杂度o(n)
首先想到直接依次遍历,复杂度n三次方
package shuzu;
import java.util.Scanner;
public class Shuzu {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int[] a = new int[5];
// 控制台输入数组值
for (int i = 0; i < a.length; i++) {
System.out.println("请输入第" + (i + 1) + "个数字:");
int num = sc.nextInt();
a[i] = num;
}
int max=a[0];
sc.close();
for(int j=0;j<a.length;j++) {
for(int k=0;k<a.length;k++) {
int sum= 0;
for(int l=0;l<a.length;l++) {
sum+=a[l];
}
if(sum>max) max=sum;
}
}
System.out.println(max);
return;
}
import java.util.Scanner;
public class Shuzu {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int[] a = new int[5];
// 控制台输入数组值
for (int i = 0; i < a.length; i++) {
System.out.println("请输入第" + (i + 1) + "个数字:");
int num = sc.nextInt();
a[i] = num;
}
int max=a[0];
sc.close();
for(int j=0;j<a.length;j++) {
for(int k=0;k<a.length;k++) {
int sum= 0;
for(int l=0;l<a.length;l++) {
sum+=a[l];
}
if(sum>max) max=sum;
}
}
System.out.println(max);
return;
}
}
后来想到一个新的方法
package shuzu;
import java.util.Scanner;
public class shuzu2 {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc = new Scanner(System.in);
int[] a = new int[20];
// 控制台输入数组值
for (int i = 0; i < a.length; i++) {
System.out.println("请输入第" + (i + 1) + "个数字:");
int num = sc.nextInt();
a[i] = num;
}
sc.close();
int max=a[0];
int sum=a[0];
for(int i=1;i<a.length;i++) {
if(sum<0)
sum=a[i];
else
sum+=a[i];
if(sum>max) max=sum;
}
System.out.println(max);
}
import java.util.Scanner;
public class shuzu2 {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc = new Scanner(System.in);
int[] a = new int[20];
// 控制台输入数组值
for (int i = 0; i < a.length; i++) {
System.out.println("请输入第" + (i + 1) + "个数字:");
int num = sc.nextInt();
a[i] = num;
}
sc.close();
int max=a[0];
int sum=a[0];
for(int i=1;i<a.length;i++) {
if(sum<0)
sum=a[i];
else
sum+=a[i];
if(sum>max) max=sum;
}
System.out.println(max);
}
}