最大子序列和


//maxSubsquenceSum.h

#ifndef MAXSUNSQUENCESUM_H
#define MAXSUNSQUENCESUM_H

#include <stdio.h>

int maxSubsquenceSum(int *, int);

#endif

//maxSubsquenceSum.c

#include "MaxSubsequenceSum.h"

int maxSubsquenceSum(int array[], int size)
{
	int thisSum,maxSum;
	int i;
	
	thisSum = maxSum = 0;
	for (i = 0; i < size; i++)
	{
		thisSum += array[i];

		if(thisSum > maxSum)
			maxSum = thisSum;
		else if(thisSum < 0)
			thisSum = 0;
	}
	return maxSum;
}

//main.c

#include "MaxSubsequenceSum.h"

int main(void)
{
	int array[] = {-2,3,5,6,-3};
	int size = sizeof(array)/sizeof(*array);//注意
	int MaxSum = maxSubsquenceSum(array,size);

	printf("the MaxSubsquenceSum is %d\n",MaxSum);
	return 0;

}
思路:将数组中从第一个元素开始依次累加存到临时的thisSum变量中,加一次中间有个判断,即与maxSum比较,大的存到maxSum中,如果thisSum小于0,说明现在遍历的这个负数比较大,再往后累加肯定比从0开始累加小,所以把thisSum置0,从新开始后面的累加。

你可能感兴趣的:(最大子序列和)