The largest sub-segment copy

Original: http: //xiaying-hefei.javaeye.com/blog/752299

 

Dynamic Programming:

      It is similar to divide and conquer, the basic idea is to solve the problem will be broken down into several sub-questions, the first sub-problem solving, solution of the original problem and the solution obtained from these sub-issues. And divide and conquer different is suitable for solving the problem of dynamic programming method, sub-problems by decomposition often not independent.

      We use a table to record the answers from all the problems have been resolved. Dynamic programming method is usually used to solve the problem with some of the best properties. In such matters, each solution corresponds to a value, we hope to find a solution that has the best value.

 

problem:

      Given by the n integers (may be negative integers) consisting of a sequence a1, a2, ..., an, and a maximum seek sub-segments of the sequence. Define its largest sub-segment when all are negative integers and zero. For example: (- 2,11, -4,13, -5, -2), and the maximum field of -4 + 11 + 13 = 20

 

code show as below:

#include <stdio.h>

// 定义b[j]为a[i]...a[j]的最大子段和。则当b[j-1] > 0时,b[j] = b[j-1] + a[j],否则b[j] = a[j]
int maxSum(int *v, int n) {
	
	int sum = 0, b = 0;
	int i;
	for(i = 1; i <= n; i++) {
		if(b > 0) b += v[i];
		else b = v[i];
		if(b > sum) sum = b;
	}
	return sum;
}

void main() {
	
	int a[] = { 0, -2, 11, -4, 13, -5, -2 };
	printf("%d\n", maxSum(a, 6));
}

Reproduced in: https: //www.cnblogs.com/anotherday/archive/2010/11/25/1887548.html

Guess you like

Origin blog.csdn.net/weixin_33904756/article/details/94515215