1 #include <stdio.h> 2 #include <stdlib.h> 3 /*求子數組最大和,時間複雜度o(n),數組有正、負整數*/ 4 /*分析,要求時間複雜度o(n),則只能讀一次數組,順序求解 5 *由於有正數,全部排除負和。 6 *可使用動態機分析。max(x[i])分兩種狀況,max(x[i-1])<=0和max(x[i-1])>0 7 */ 8 #define len(x) (sizeof(x)/sizeof(x[0])) 9 int bigsum_subarray(int *x, int len) 10 { 11 if(x == NULL || len <= 0) 12 return -1; 13 14 int i, total = 0, tmp = 0; 15 16 for(i = 0; i < len; i++){ 17 if(tmp <= 0) 18 tmp = x[i]; 19 else 20 tmp += x[i]; 21 if(tmp > total) 22 total = tmp; 23 } 24 return total; 25 } 26 int main(void) 27 { 28 int total, x[] = {1, -2, 3, -10, -4, 7, 15, -5}; 29 30 total = bigsum_subarray(x, len(x)); 31 32 printf("%d\n", total); 33 return 0; 34 }