在一个字符串中取得连续的子序列,并保证该序列各元素的和,为所有子序列中最大的。
import java.util.Scanner;
//和最大的子串
public class ZichuanQiuhe {
public static void main(String args[])
{
Scanner sc= new Scanner(System.in);
int tmp = sc.nextInt();
int temp[] = new int[tmp]; //对相关数列进行录入
int top = 0,max = 0,begin = 1,last = 1,rebegin = 1;
for(int i = 0;i<temp.length;i++) //数据录入
{
temp[i] = sc.nextInt();
}
for(int j = 0 ; j < temp.length; j++) //求最大值操作
{
top+=temp[j];
if(top>max)
{
begin = rebegin; //记录起始点,并实现起始点的更新与替换
max = top; //子序列的最大值
last = j+1; //记录末尾点,随着数据的累和,向后逐渐更新
}
if(top < 0)
{
rebegin = j+2;
top = 0;
}
}
System.out.println("最大值="+max);
System.out.println("起始位置="+begin+","+"终点位置="+last);
}
}
388



被折叠的 条评论
为什么被折叠?



