输出一个序列的最大子序列的和,以及该最大子序列的第一个和最后一个元素(不是索引)
#include<stdio.h>
#include<malloc.h>
#include<stdlib.h>
int* newArray(int length);
int maxSubSum(int* arr, int length, int* first, int* last);
int main(void) {
int K, first, last; //分别对应:元素总数,最大子列第一个元素下标,最大子列最后一个元素下标
scanf("%d", &K);
int* arr = newArray(K);
for (int i = 0; i < K; i++)
scanf("%d", &arr[i]);
first = 0, last = K - 1;
int maxSum = maxSubSum(arr, K, &first, &last);
printf("%d %d %d", maxSum, arr[first], arr[last]);
return 0;
}
int* newArray(int length) {
int* arr = (int*)malloc(sizeof(int) * length);
if (arr == NULL) {
printf("Error\n");
exit(-1);
}
return arr;
}
int maxSubSum(int* arr, int length, int* first, int* last) {
int maxSum = -1, tempSum = 0, temp = 0;
for (int i = 0; i < length; i++) {
tempSum += arr[i];
if (tempSum > maxSum) {
maxSum = tempSum;
*last = i;
*first = temp;
}
if (tempSum < 0) {
tempSum = 0;
//if (i + 1 <= *last) //加了出错,例子:5 -6 -2 99
temp = i + 1;
}
}
return maxSum > 0 ? maxSum : 0;
}