- 论坛徽章:
- 0
|
本帖最后由 shimmey 于 2012-04-08 10:30 编辑
周末将楼主的函数稍作修改,可以输出子数组的范围了。- int foo1( int *pData, unsigned int length, int **start, int *len )
- {
- int cursum = 0;
- int sum = 0;
- int max = pData[0];
- int i = 0;
- int idx = 0;
- int idx_max = 0;
-
- if( pData == NULL || length == 0 )
- return ERR;
- *start = pData;
- for (; i < length; i++)
- {
- cursum += pData[i];
-
- if (pData[i] > max)
- {
- max = pData[i];
- idx_max = i;
- }
- if (cursum < 0)
- {
- cursum = 0;
- idx = i + 1;
- }
- if (cursum > sum)
- {
- sum = cursum;
- *start = pData + (idx > length ? length : idx);
- *len = pData + i - *start + 1;
- }
- }
- if (sum == 0)
- {
- sum = max;
- *start = pData + idx_max;
- *len = 1;
- }
- return sum;
- }
- int main(int argc, char *argv[])
- {
- int buf1[] = { 2, 3, -6, 3, 4, 3, -2, 5, 2, -3, -4, -2 }; // Sum(3,8)=15
- int *start = NULL;
- int len = 0;
- int sum = 0;
-
- sum = foo1(buf1, sizeof(buf1)/sizeof(buf1[0]), &start, &len);
- printf( "sum=%d, start[%d], length[%d]\n", sum, start-buf1, len );
-
- return 0;
- }
复制代码 输出结果为:sum=15, start[3], length[6]
|
|