思路:
采用动态规划进行求解,令:
maxSum[k]表示子串list{0,k}的最大连续子串和,
maxSumIncludeK[k]表示子串list{0,k}中末尾为k的最大连续子串和,
则
maxSumIncludeK[k] = max(list[k],list[k]+maxSumIncludeK[k-1]),
maxSum[k] = max(maxSumIncludeK[k],maxSum[k-1])。
代码:
- #include <stdlib.h>
- #include <stdio.h>
- int MaxSubList(int list[],int length)
- {
- int i;
- //maxSum[k]表示子串list{0,k}的最大连续子串和
- //maxSumIncludeK[k]表示子串list{0,k}中末尾为k的最大连续子串和
- int* maxSum = (int*)malloc(sizeof(int)*length);
- int* maxSumIncludeK = (int*)malloc(sizeof(int)*length);
- for (i=0;i<length;i++)
- {
- maxSum[i] = 0;
- maxSumIncludeK[i] = 0;
- }
- if (list[0]>0) maxSum[0] = list[0];
- maxSumIncludeK[0] = list[0];
- for (i=1;i<length;i++)
- {
- maxSumIncludeK[i] = list[i];
- if (maxSumIncludeK[i-1]>0) maxSumIncludeK[i]+=maxSumIncludeK[i-1];
- if (maxSumIncludeK[i]>maxSum[i-1]) maxSum[i] = maxSumIncludeK[i];
- else maxSum[i] = maxSum[i-1];
- }
- return maxSum[length-1];
- }
- int main()
- {
- int list[20] = {4,9,-4,3,2,-1,-6,7,2,-3,1,5,3,-2,7,-3,9,2,-4,2};
- printf("max sum:%d \n",MaxSubList(list,20));
- return 0;
- }
转载于:https://blog.51cto.com/zephiruswt/887585