标签:求最大子数组
一个数组,长度为N,数组元素有负有正,如{-1, 4, 6, -3, 7, -3, -3, 9};我们可以清楚的知道最大的子数组应该是4到9,也就是下标1到下标7,和为17。
int MaxSubArraySum(int a[], int N, int &start, int &end) { int ThisSum, MaxSum, i, j; *start = 0; *end = 0; MaxSum = 0; for (i = 0; i < N; ++i) { ThisSum = 0; for (j = i; j < N; ++j) { ThisSum += a[j]; if (ThisSum > MaxSum) { *start = i; *end = j; MaxSum = ThisSum; } } } return MaxSum; }5、此方法的时间复杂度很明显为(O(N^2))
int maxSubArraySum(int[] arr, int N, int &start, int end) { int maxSum = 0; int thisSum = 0; int i; *start = 0; *end = 0; for (i = 0; i < N; i++) { thisSum += arr[i]; if (thisSum > maxSum){ maxSum = thisSum; *end = i; } if (thisSum < 0){ thisSum = 0; if(i <= N - 2 && arr[i+1] > 0){ *start = i + 1; } } } //如果最大子数组不在数组里面的话(数组元素全部<=0),start,end赋值为-1 if(*start == 0 && *end == 0 && arr[0] <= 0){ *start = -1; *end = -1; } return maxSum; }
求最大子数组的和,以及求该最大子数组的起始位置和末尾位置,布布扣,bubuko.com
标签:求最大子数组
原文地址:http://blog.csdn.net/dafeng_blog/article/details/25336931