开发者

Maximum Contiguous Subsequence Sum with longest sequence?

开发者 https://www.devze.com 2023-02-14 12:16 出处:网络
I know how to find a maximum, contiguous, subsequence sum; but sometimes there\'s more than one subsequence with maximum sum.So, I need to find the index of those longest subsequences with the maximum

I know how to find a maximum, contiguous, subsequence sum; but sometimes there's more than one subsequence with maximum sum. So, I need to find the index of those longest subsequences with the maximum sum. The only thing I thought of is brute force. What better options are there?

Here's a code I found on rosettacode which had the exact idea for my problem (but, sadly, the only programming language I know is Java), but it is writen in REXX:

/*───────────────────────────────────────────────────────────────*/
arg @                                  
say 'words='words(@) 'list='@          
say
sum=word(@,1)                          
w=words(@)                             
at=1                                   
L=0       

do j=1 for w;  f=word(@,j)

    do k=j to w; s=f

          do m=j+1 to k
          s=s+word(@,m)
          开发者_如何学JAVAend   /*m*/

    _=k-j+1
    if (s==sum & _>L) | s>sum then do; sum=s; at=j; L=_; end
    end         /*k*/

end               /*j*/


seq=subword(@,at,L)
if seq=='' then seq="[NULL]"
sum=word(sum 0,1)
say 'sum='sum/1 "sequence="seq
/*───────────────────────────────────────────────────────────────*/

Results:

input 1 2 3 4 -777 1 2 3 4 0 0 
output
words=12 list=1 2 3 4 0 -777 1 2 3 4 0 0

sum=10 sequence=1 2 3 4 0 0


If this is homework, I'd recommend you take a look at dynamic programming algorithms. In particular, you can simplify one of the steps of the Smith-Waterman local string alignment to do exactly what's needed here. The key is to read up on the idea of optimal substructure and ask yourself, is there some kind of subproblem involved which I can solve using only local information at each point in the sequence?

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号