Maximum run between identical elements This is a overhaul of this now deleted question by ar kang. If the OP of that question would like to reclaim this question or has a problem with me posting this I'd be happy to accommodate


Given a list of integers as input find the maximum possible sum of a continuous sublist that starts and ends with the same value.  The sublists must be of length at least 2.  For example for the list 

[1, 2, -2, 4, 1, 4]


There are 2 different continuous sublists start and end with the same value

[1,2,-2,4,1] -&gt; 6
[4,1,4]      -&gt; 9


The bigger sum is 9 so you output 9.

You may assume every input contains at least 1 duplicate.

This is code-golf so answers will be scored in bytes with fewer bytes being better.

Test cases

[1,2,-2,4,1,4]  -&gt; 9
[1,2,1,2]       -&gt; 5
[-1,-2,-1,-2]   -&gt; -4
[1,1,1,8,-1,8]  -&gt; 15
[1,1,1,-1,6,-1] -&gt; 4
[2,8,2,-3,2]    -&gt; 12
[1,1,80]        -&gt; 2
[2,8,2,3,2]     -&gt; 17
Haskell, 62 bytes

f takes a list of integers and returns an integer.



f l=maximum[x+sum m-sum n|x:m&lt;-t l,y:n&lt;-t m,x==y]
t=scanr(:)[]


Try it online!

How it works


t is the standard "get all suffixes of a list without importing Data.List.tails" function.
In f l, the list comprehension iterates through all the non-empty suffixes of the argument list l, with first element x and remainder m.
For each, it does the same for all nonempty suffixes of m, selecting first element y and remainder n.
If x and y are equal, the list comprehension includes the sum of the elements between them. This sublist is the same as x:m with its suffix n stripped off, so the sum can be calculated as x+sum m-sum n.