浙江大学考研题,最大子序列和及首尾项
package exercise;
import java.util.Scanner;
public class week1 {
public static int[] maxSequence(int K, int A[])
{
int maxsum = 0;
int markleft = 0;
int markright = 0;
int [] need = new int[3];
for (int x = 0; x < K; x++)
{
markleft = A[x];
int thissum = 0;
for (int y = x; y < K; y++)
{
markright = A[y];
thissum += A[y];
if (thissum > maxsum)
{
maxsum = thissum;
need[0] = maxsum;
need[1] = markleft;
need[2] = markright;
}
else
{
markleft = 0;
markright = 0;
}
}
}
return need;
}
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
int K = in.nextInt();
int []sum = new int[2];
int []A = new int[K];
for (int i = 0; i < K; i++)
{
A[i] = in.nextInt();
}
sum = maxSequence(K, A);
for (int j = 0; j < 3; j++)
{
System.out.print(sum[j]);
if (j < 2)
{
System.out.print(" ");
}
}
in.close();
}
}