1. 程式人生 > 實用技巧 >最大子序列和問題

最大子序列和問題

1.遞迴

該方法由書上提供,比較好理解:給定一個數組,從中間劃分成兩個陣列[1,mid],[mid+1,end];a.位於左半邊 b.位於右半邊 c.跨越兩邊。求兩邊最大子序列時可遞迴求解,求跨越兩邊的子序列時分別從mid、mid+1出發,求得left_sum和right_sum,相加即為跨越兩邊的最大子序列和。

程式碼:

#include <stdio.h>
#include <stdlib.h>

int Find_Mid_Max(int* q,int start,int end) {
    int mid = (start + end) / 2;
    int
left_sum = 0; int right_sum = 0; int sum = 0; int i; for (i = mid;i > 0;i--) { sum += q[i]; if (sum > left_sum) left_sum = sum; } sum = 0; for (i = mid+1;i <=end;i++) { sum += q[i]; if (sum > right_sum) right_sum
= sum; } return left_sum + right_sum; } int Find_Max(int* q, int start, int end) { int maxsum = 0; if (start == end) { if (q[end] > maxsum) maxsum = q[end]; return maxsum; } int mid = (start + end) / 2; int left=Find_Max(q, start, mid); int
right = Find_Max(q, mid + 1, end); int across = Find_Mid_Max(q, start, end); if (left > right && left > across) maxsum = left; else if (right > across) maxsum = right; else maxsum = across; return maxsum; } int main() { int k; if (scanf("%d", &k) == 0){} int* q = (int*)malloc(sizeof(int) *(k+1)); int i; for (i = 1;i <= k;i++) { if(scanf("%d",&q[i])==0){} } int max=Find_Max(q, 1, k); printf("%d", max); return 0; }