介个题与前面leetcode分析的那个题一模一样捏
比较(a[i]+a[i+1])的值和a[i+1]的值,如果大于的话则继续,如果小于的话则从a[i+1]开始。用for循环寻找最大和的连续子数组。
import java.util.Scanner;
public class MaxSum {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc=new Scanner(System.in);
// System.out.println("输入数组长度");
// int n=sc.nextInt();System.out.println("输入数组数据(用空格分开)");
int i;
int a[]={-2,11,-4,13,-5,-2};
// for(i=0;i<n;i++)
// a[i]=sc.nextInt();
int begin=0;//子数组开始下标
int end=0;//子数组结束下标
int maxValue=a[0];
int tempValue=maxValue;
//for循环寻找最大和的连续子数组
for(i=1;i<5;i++)
{
tempValue+=a[i];
if((tempValue>a[i])&&(tempValue>maxValue))//相邻两个数的和大于第二个数并且大于当前值
{
end=i;
maxValue=tempValue;
}
else if(tempValue<=a[i])//小的话,从第二个数开始
{
begin=i;
end=i;
tempValue=a[i];
}
}
//输出最大和的连续子数组的相关信息
System.out.println("最大子数组和为:"+maxValue+"\n子数组内容为:");
System.out.println("下标:");
for(i=begin;i<=end;i++)
System.out.print(i+" ");
System.out.println("\n"+"下标对应数值:");
for(i=begin;i<=end;i++)
System.out.print(a[i]+" ");
}
}