标签:
看见这个问题你的第一反应是用什么算法?
(1) 枚举?对,枚举是万能的!枚举什么?子数组的位置!好枚举一个开头位置i,一个结尾位置j>=i,再求a[i..j]之间所有数的和,找出最大的就可以啦。好的,时间复杂度?
for(int i = 1; i <= n; i++) { for(int j = i; j <= n; j++) { int sum = 0; for(int k = i; k <= j; k++) sum += a[k]; max = Max(max, sum); } }
for(int i = 1; i <= n; i++) { int sum = 0; for(int j = i; j <= n; j++) { sum += a[j]; max = Max(max, sum); } }
endmax = answer = a[1] for i = 2 to n do endmax = max(endmax, 0) + a[i] answer = max(answer, endmax) endfor
start = 1 answerstart = asnwerend = 1 endmax = answer = a[1] for end = 2 to n do if endmax > 0 then endmax += a[end] else endmax = a[end] start = end endif if endmax > answer then answer = endmax answerstart = start answerend = end endif endfor
第1行:整数序列的长度N(2 <= N <= 50000) 第2 - N + 1行:N个整数(-10^9 <= A[i] <= 10^9)
输出最大子段和。
6 -2 11 -4 13 -5 -2
20
1 def max(a,b): 2 if a>b: 3 return a 4 else: 5 return b 6 7 n=int(input().split()[0]) 8 endmax=0 9 ans=-10000000000 10 for i in range(n): 11 a=int(input().split()[0]) 12 endmax=max(0,endmax)+a 13 ans=max(ans,endmax) 14 15 print(ans)
标签:
原文地址:http://www.cnblogs.com/nbalive2001/p/4757142.html