In python, how does one efficiently find the largest consecutive set of numbers in a list that are not necessarily adjacent?

前端 未结 10 772

For instance, if I have a list

[1,4,2,3,5,4,5,6,7,8,1,3,4,5,9,10,11]

This algorithm should return [1,2,3,4,5,6,7,8,9,10,11].

To cl

10条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-31 11:53

    You need the Maximum contiguous sum(Optimal Substructure):

    def msum2(a):
        bounds, s, t, j = (0,0), -float('infinity'), 0, 0
    
        for i in range(len(a)):
            t = t + a[i]
            if t > s: bounds, s = (j, i+1), t
            if t < 0: t, j = 0, i+1
        return (s, bounds)
    

    This is an example of dynamic programming and is O(N)

提交回复
热议问题