Time Limit: 5 ms Memory Limit: 500 KiB
Submit Statistic
Problem Description
给定n(1<=n<=100000)个整数(可能为负数)组成的序列a[1],a[2],a[3],…,a[n],求该序列如a[i]+a[i+1]+…+a[j]的子段和的最大值。当所给的整数均为负数时定义子段和为0,依此定义,所求的最优值为: Max{0,a[i]+a[i+1]+…+a[j]},1<=i<=j<=n。 例如,当(a[1],a[2],a[3],a[4],a[5],a[6])=(-2,11,-4,13,-5,-2)时,最大子段和为20。
注意:本题目要求用动态规划法求解,只需要输出最大子段和的值。
Input
第一行输入整数n(1<=n<=100000),表示整数序列中的数据元素个数;
第二行依次输入n个整数,对应顺序表中存放的每个数据元素值。
Output
输出所求的最大子段和
Sample Input
6 -2 11 -4 13 -5 -2Sample Output
20Hint
Source
思路:这个求最大字段和的方法效率高,而且很好理解。 遍历一遍即可,ans用来存最大,max用来记录各个字段和,如果max小于0的时候,后面只会使得字段和更小,所以更新为0,如果大于ans就让ans等于它 就这样遍历一遍。
AC代码:
#include<stdio.h> #include<stdlib.h> typedef struct node { int data[100010]; int last; }ST; int main() { ST *head; int max, i, ans; head = (ST *)malloc(sizeof(ST)); while(~scanf("%d", &head->last)) { max = 0; ans = 0; for(i = 0; i < head->last; i++) { scanf("%d", &head->data[i]); } for(i = 0; i < head->last; i++) { if(max + head->data[i] > ans) ans = max + head->data[i]; if(max + head->data[i] < 0) max = 0; else { max += head->data[i]; } } printf("%d\n", ans); } return 0; }