Mercurial > lbo > hg > juliaplay
changeset 11:ffb42007e4de
dp: target_sum
author | Lewin Bormann <lbo@spheniscida.de> |
---|---|
date | Sun, 19 Feb 2023 19:20:34 +0100 |
parents | 27f59dd007ab |
children | cb419167dcb3 |
files | python/dp.py |
diffstat | 1 files changed, 13 insertions(+), 0 deletions(-) [+] |
line wrap: on
line diff
--- a/python/dp.py Sun Feb 19 16:35:57 2023 +0100 +++ b/python/dp.py Sun Feb 19 19:20:34 2023 +0100 @@ -181,3 +181,16 @@ bestcoord = (x, y) return bestcoord, bestsum +def target_sum(s, target): + sums = np.zeros_like(s) + for i in range(len(s)): + sums[i] = sums[max(0, i-1)] + s[i] + + maxlen = -1 + firstix, lastix = None, None + for i in range(len(s)): + for j in range(i+1, len(s)): + if sums[j]-(sums[i-1] if i > 0 else 0) == target and (j-i+1) > maxlen: + maxlen = j-i+1 + firstix, lastix = i, j + return (firstix, lastix)