Maximum Contiguous Subsequence Sum of At Least Length L

后端 未结 5 1982
北海茫月
北海茫月 2020-12-01 01:53

So for the following array, where L = 3

-5 -1 2 -3 0 -3 3

The best possible sum of at least length 3 would be 0, where the subsequence is t

5条回答
  •  萌比男神i
    2020-12-01 02:31

    Useless cases and definitions, etc. My solution is the natural one. First of all, keep this in mind, we are looking for the maximum sum of a contiguous fragment of an array of integers, that fragment has more than or exactly L elements. Let's name A the initial array. For the same reasons like in Kadane's algorithm, we consider an auxiliary array, REZ, having N elements, like A, REZ[i] means the maximum sum of a contiguous fragment of A, containing at least L elements and ending exactly at the i-th position. Of course, REZ[1], RZ[2], REZ[L-1] are all equal with a ZERO or -INFINITY value. REZ[L]=A[1]+A[2]+...+A[L]. For the rest of the values in REZ, from i growing from L+1 to N, to calculate REZ[i] we have to choose the maximum between two cases:

    1. a fragment of exactly L values and containing A[i]
    2. a fragment having more than L values and containing A[i]

    The result for the first case can be calculated instantly with the partial sum array (S[i]=A[1]+A[2]+...+A[i]), S[i]-S[i-L]. The result for the second case is REZ[i-1]+A[i]. So,

    • REZ[i]=-INFINITY, if 1<=i<=L-1
    • REZ[i]=S[i], if i=L
    • REZ[i]=max(S[i]-S[i-L], REZ[i-1]+A[i]), if i>L.

    After REZ was built we have to calculate its maximum value. Let's consider the following example:

    N=7

    A -5 -1 2 -3 0 -3 3

    L=3

    S -5 -6 -4 -7 -7 -10 -7

    REZ: -INF -INF -4

    REZ[4]=max(S[4]-S[4-3],REZ[3]+A[4])=max(-2, -7)=-2

    REZ: -INF -INF -4 -2

    REZ[5]=max(S[5]-S[5-3],REZ[4]+A[5])=max(-1,-2)=-1

    REZ: -INF -INF -4 -2 -1

    REZ[6]=max(S[6]-S[6-3], REZ[5]+A[6])=max(-6,-4)=-4

    REZ: -INF -INF -4 -2 -1 -4

    REZ[7]=max(S[7]-S[7-3],REZ[6]+A[7])=max(0,-1)= 0

    REZ: -INF -INF -4 -2 -1 -4 0

    The maximum value in REZ is 0 and this is the answer for the whole problem.

    I hope my English is good enough. I am searching for a solution for a similar problem, when the result must have at most L consecutive elements. When I realised that the methods described above were actually for solutions having at least L elements, I was quite disappointed.

提交回复
热议问题