[資料結構]01-複雜度2 Maximum Subsequence Sum
阿新 • • 發佈:2018-12-01
#include<stdio.h> #include <string.h> #define size 100050 int begin = 0, end = 0; int b = 0, e = 0; //定義成全域性變數方便修改 int FindMax(int a[], int n); int main(void) { int num; scanf("%d", &num); int str[size] = { 0 }; for (int i = 0; i < num; i++) { scanf("%d", &str[i]); } int sum=FindMax(str, num); printf("%d %d %d\n", sum,begin,end); return 0; } int FindMax(int a[], int n) { int maxsub=0, thissub = 0; int flag = 0; for (int i = 0; i < n; i++) { if (!b) { b = a[i]; //暫時儲存開頭 } if (a[i] >= 0) { flag = 1; //判斷是否全為0 } thissub += a[i]; if (thissub > maxsub) { e = a[i]; begin = b; end = e; //儲存開頭結尾 maxsub = thissub; } else if (thissub < 0) { b = 0; //清空 e = 0; thissub = 0; } } if (!flag) { begin = a[0]; end = a[n - 1]; } return maxsub; }