题目:https://pintia.cn/problem-sets/15/problems/709
给定K个整数组成的序列{ N1,N2,⋯,Nk N 1 , N 2 , ⋯ , N k },“连续子列”被定义为{ Ni,Ni+1,⋯,Nj N i , N i + 1 , ⋯ , N j },其中 1≤i≤j≤K 1 ≤ i ≤ j ≤ K 。“最大子列和”则被定义为所有连续子列元素的和中最大者。例如给定序列{ -2, 11, -4, 13, -5, -2 },其连续子列{ 11, -4, 13 }有最大的和20。现要求你编写程序,计算给定整数序列的最大子列和。
本题旨在测试各种不同的算法在各种数据情况下的表现。各组测试数据特点如下:
数据1:与样例等价,测试基本正确性;
数据2:102个随机整数;
数据3:103个随机整数;
数据4:104个随机整数;
数据5:105个随机整数;
输入格式:
输入第1行给出正整数K (≤100000);第2行给出K个整数,其间以空格分隔。
输出格式:
在一行中输出最大子列和。如果序列中所有整数皆为负数,则输出0。
输入样例:
6
-2 11 -4 13 -5 -2
输出样例:
20
代码1: T(n)=O(n2) T ( n ) = O ( n 2 )
#include <stdio.h>
//#include <time.h>
#define MAX 100000
//clock_t start, stop;
//double duration;
int main(void)
{
//start = clock();
//stop = clock();
int K, i, arr[MAX];
int k, maxSum, tempSum;
scanf("%d", &K);
for(i=0; i<K; i++){
scanf("%d", &arr[i]);
}
maxSum = 0;
for(i=0; i<K; i++){
tempSum = 0;
for(k=i; k<K; k++){
tempSum += arr[k];
if(tempSum>maxSum){
maxSum = tempSum;
}
}
}
printf("%d\n", maxSum);
return 0;
}
代码2:在线处理 T(n)=O(n) T ( n ) = O ( n )
#include <stdio.h>
//#include <time.h>
#define MAX 100000
//clock_t start, stop;
//double duration;
int main(void)
{
//start = clock();
//stop = clock();
int K, i, arr[MAX];
int maxSum, tempSum;
scanf("%d", &K);
for(i=0; i<K; i++){
scanf("%d", &arr[i]);
}
maxSum = 0;
tempSum = 0;
for(i=0; i<K; i++){
tempSum += arr[i];
if(tempSum>maxSum){
maxSum = tempSum;
}
if(tempSum<0){
tempSum = 0;
}
}
printf("%d\n", maxSum);
return 0;
}