标签:utf-8 python style subject 最大连续 bottom http 说明 desc
我们很自然地能想到穷举的办法,穷举所有的子数组的之和,找出最大值。
i, j的for循环表示x[i..j],k的for循环用来计算x[i..j]之和。
maxsofar = 0
for i = [0, n)
for j = [i, n)
sum = 0
for k = [i, j]
sum += x[k]
/* sum is sum of x[i..j] */
maxsofar = max(maxsofar, sum)
有三层循环,穷举法的时间复杂度为O(n3)。
我们注意到x[i..j]之和 = x[i..j-1]之和 + x[j],因此在j的for循环中,可直接求出sum。
maxsofar = 0
for i = [0, n)
sum = 0
for j = [i, n)
sum += x[j]
/* sum is sum of x[i..j] */
maxsofar = max(maxsofar, sum)
改进之后的时间复杂度变为o(n2)
在计算fibonacci数时,应该还有印象:用一个累加数组(cumulative array)记录前面n-1次之和,计算当前时只需加上n即可。同样地,我们用累加数组cumarr记录:cumarr[i] = x[0] + . . . +x[i],那么x [i.. j]之和 = cumarr[j] -cumarr[i - 1]。
cumarr[-1] = 0
for i = [0, n)
cumarr[i] = cumarr[i-1] + x[i]
maxsofar = 0
for i = [0, n)
for j = [i, n)
sum = cumarr[j] - cumarr[i-1]
/* sum is sum of x[i..j] */
maxsofar = max(maxsofar, sum)
时间复杂度为o(n2)
最大和连续子数组一定有如下几个特点:
1、定义两个变量,一个用来存储之前的累加值,一个用来存储当前的最大和。遍历数组中的每个元素,假设遍历到第i个数时:
①如果前面的累加值为负数或者等于0,那对累加值清0重新累加,把当前的第i个数的值赋给累加值。
②如果前面的累加值为整数,那么继续累加,即之前的累加值加上当前第i个数的值作为新的累加值。
2、判断累加值是否大于最大值:如果大于最大值,则最大和更新;否则,继续保留之前的最大和。
# -*- coding:utf-8 -*-
class Solution:
def FindGreatestSumOfSubArray(self, array):
# write code here
max_sum = array[0]
pre_sum = 0
for i in array:
if pre_sum < 0:
pre_sum = i
else:
pre_sum += i
if pre_sum > max_sum:
max_sum = pre_sum
return max_sum
分治法,动态规划,未完待续
标签:utf-8 python style subject 最大连续 bottom http 说明 desc
原文地址:https://www.cnblogs.com/tianqizhi/p/9819702.html