计算数组的最大子数组之和(人搜)

看见这个题目,就知道这是一个典型的动态规划问题,代码如下:

/*************************************************************
 * file:calmax_child_array_sum.c
 * brief:基于DP,计算数组的子数组的最大和,返回起始终止索引
	暴力的解法复杂度是O(n^2)
	动态规划的复杂度为O(n),因为可以基于之前计算的和做参考
 * [email protected]    1.0      creat
 *************************************************************/
 #include 
 #include 

void dp_calmax_child_array_sum(int array[], int n, int* start_index, int* end_index, int* max_sum){
	if(!array || !n)
		return;
	int tmp_max = 0;
	int i = 0;
	while(i < n){
		//之前的是负数或者0,重新开始,记录起始索引
		if(tmp_max <= 0){
			*start_index = i;
			tmp_max = array[i];
		}
		else
			tmp_max += array[i];
			
		//找到一个更大,更新最大值,记录终止索引
		if(tmp_max > *max_sum){
			*max_sum = tmp_max;
			*end_index = i;
		}
		++i;
	}
	return;
}

int main(int argc, char* argv[]){
	int array[] = {1, -2, 3, -4, 6, 7, -10, 4, 5, 6, -1};
	int start_index, end_index, max_sum;
	dp_calmax_child_array_sum(array, sizeof(array)/sizeof(int), &start_index, &end_index, &max_sum);
	
	printf("start_index:%d, end_index:%d, max_sum:%d \n", start_index, end_index, max_sum);
	
	return 1;
}

但是以上代码如果在充分测试下应该是有问题的,

比如:无法处理全是负数的数组(实际上是需要找到最大 的负数),暂时没有想到太好的办法,先贴上来,回家update。

你可能感兴趣的:(algorithms)