求最大子数组和的6个版本

#include <stdio.h>
#define INF ( (1 << 30) - 1 )
#define SIZE 100

int maxSubArrayV1(int array[], int size){
	int maxSum = -INF;
	int start, end;
	for (start = 0; start < size; start++)
		for (end = start; end < size; end++){
			//sum中很多数组元素值重复计算,可优化
			int sum = 0;
			int i;
			for (i = start; i <= end; i++)
				sum += array[i];
			if (sum > maxSum)
				maxSum = sum;
			
		}
	return maxSum;
}

int maxSubArrayV2(int array[], int size){
	int maxSum = -INF;
	int start, end;
	for (start = 0; start < size; start++){
		//sum用来保存上次计算的和,每次只需加上新的数组元素值
		int sum = 0;
		for (end = start; end < size; end++){
			sum += array[end];
			if (sum > maxSum)
				maxSum = sum;
		}
	}
	return maxSum;
}

int maxSubCrossingArray(int array[], int first, int center, int last){
	int leftMaxSum = -INF;
	int sum = 0;
	int i;
	for (i = center; i >= first; i--){
		sum += array[i];
		if (sum > leftMaxSum)
			leftMaxSum = sum;
	}

	int rightMaxSum = -INF;
	for (i = center + 1; i <= first; i++){
		sum += array[i];
		if (sum > rightMaxSum)
			rightMaxSum = sum;
	}

	return leftMaxSum + rightMaxSum;
}
int maxSubArrayV3(int array[], int first, int last){
	if (first == last)
		return array[first] > 0 ? array[first] : 0;

	int center = (first + last) >> 1;
	//分治
	int leftMaxSum = maxSubArrayV3(array, first, center);
	int rightMaxSum = maxSubArrayV3(array, center + 1, last);
	int maxSum = maxSubCrossingArray(array, first, center, last);
	
	if (leftMaxSum > maxSum)
		maxSum = leftMaxSum;

	if (rightMaxSum > maxSum)
		maxSum = rightMaxSum;

	return maxSum;
}

int maxSubArrayV4(int array[], int size){
	//maxSumWithTail[tail]表示以元素array[tail]为结尾的最大字数组的和
	//分两种情况:1.元素array[tail]和tail之前的元素组成最大字数组。2.元素array[tail]单独作为最大字数组
	int maxSumWithTail[SIZE];
	maxSumWithTail[0] = array[0] > 0 ? array[0] : 0;
	int maxSum = maxSumWithTail[0];
	int tail;
	for (tail = 1; tail < size; tail++){
		//每回只应用元素maxSumWithTail[tail - 1],所以maxSumWithTail可优化
		if (maxSumWithTail[tail - 1] > 0)
			maxSumWithTail[tail] = array[tail] + maxSumWithTail[tail - 1];
		else
			maxSumWithTail[tail] = array[tail];
		if (maxSumWithTail[tail] > maxSum)
			maxSum = maxSumWithTail[tail];
	}
	return maxSum;
}

int maxSubArrayV5(int array[], int size){
	int maxSum = 0;
	int maxSumWithTail = 0;
	int tail;
	for (tail = 0; tail < size; tail++){
		if (maxSumWithTail > 0)
			maxSumWithTail += array[tail];
		else
			maxSumWithTail = array[tail];
		if (maxSumWithTail > maxSum)
			maxSum = maxSumWithTail;
	}
	return maxSum;
}

int maxSubArrayV6(int array[], int size){
	int maxSum = -INF;
	int tempMaxSum = 0;
	int i;
	for (i = 0; i < size; i++){
		tempMaxSum += array[i];
		if (tempMaxSum > maxSum)
			maxSum = tempMaxSum;
		if (tempMaxSum < 0)
			tempMaxSum = 0;
		//当tmpMaxSum > 0时,tmpMaxSum有潜力成为最大字数组和
	}
	return maxSum;
}

int main(){
	return 0;
}


 
 
 

你可能感兴趣的:(最大子串,最大子数组和)