Recommended approach
I suggest solving this using DP where instead of tracking A,B (the size of the two sets), you instead track A+B,A-B (the sum and difference of the two sets).
Then for each element in the array, try adding it to A, or B, or neither.
The advantage of tracking the sum/difference is that you only need to keep track of a single value for each difference, namely the largest value of the sum you have seen for this difference.
For added efficiency, I recommend you iterate through the elements in order from smallest to largest and stop updating the DP once the largest difference seen so far is reached.
You can also only store the absolute value of the difference, and ignore any difference greater than 25000 (as it will be impossible for the difference to return to 0 from this point).
Python example code
from collections import defaultdict
def max_equal_sum(E):
D=defaultdict(int) # Map from abs difference to largest sum
D[0]=0 # Start with a sum and difference of 0
for a in E: # Iterate over each element in the array
D2=D.copy() # Can keep current sum and diff if element is skipped
for d,s in D.items(): # d is difference, s is sum
s2 = s+a # s2 is new sum
for d2 in [d-a,d+a]: # d2 is new difference
D2[abs(d2)] = max(D2[abs(d2)],s2) # Update with largest sum
D=D2
return D[0]/2 # Answer is half the sum of A+B for a difference of 0
print max_equal_sum([1,2,3,4,6]) # Prints 8
print max_equal_sum([4,10,18,22]) # Prints 22
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…