/*给定K个整数组成的序列{ N1, N2, ..., NK },“连续子列”被定义为{ Ni, Ni+1, ..., Nj },其中 1 <= i <= j <= K。“最大子列和”则被定义为所有连续子列元素的和中最大者。例如给定序列{ -2, 11, -4, 13, -5, -2 },其连续子列{ 11, -4, 13 }有最大的和20。现要求你编写程序,计算给定整数序列的最大子列和。输入格式:输入第1行给出正整数 K (<= 100000);第2行给出K个整数,其间以空格分隔。输出格式:在一行中输出最大子列和。如果序列中所有整数皆为负数,则输出0。输入样例:6-2
11 -4 13 -5 -2输出样例:20*/
#include<stdio.h>
#include<math.h>
#include<stdlib.h>
int main()
{
int i, size, *array;
int temp = 0;
int tempMax = 0, Max = 0;
scanf("%d", &size, 2);
if (size>0){
array = (int *)malloc(size*sizeof(int));
for (i = 0; i<size; i++)
scanf("%d", &array[i]);
for (i = 0; i<size; i++)
if (array[i] >> 0)
{
temp++;
}
for (i = 0; i < size; i++){
tempMax = tempMax + array[i];
if (tempMax < 0){
tempMax = 0;
}
else if (tempMax >= 0){
if (tempMax>Max)
Max = tempMax;
}
}
}
if (Max < 0 || temp == 0)
Max = 0;
printf("%d", Max);
return 0;
}
简化版:
#include<stdio.h>
#include<math.h>
#include<stdlib.h>
int main()
{
int i, size, *array;
int temp = 0;
int tempMax = 0, Max = 0;
scanf("%d", &size, 2);
if (size>0){
array = (int *)malloc(size*sizeof(int));
for (i = 0; i<size; i++)
scanf("%d", &array[i]);
for (i = 0; i < size; i++){
tempMax = tempMax + array[i];
if (tempMax>Max)
Max = tempMax;
else if (tempMax < 0)
tempMax = 0;
}
}
if (Max < 0)
Max = 0;
printf("%d", Max);
return 0;
}