fork download
  1. from collections import defaultdict
  2. def main(arr,k):
  3.  
  4. # ps[j]-ps[i] max:==> ps[j]-ps[i] should be minimum
  5.  
  6. n=len(arr)
  7. ps=[]
  8.  
  9. for x in arr:
  10. if len(ps) == 0:
  11. ps.append(x)
  12. else:
  13. ps.append(x+ps[-1])
  14.  
  15. hm=defaultdict(int)
  16.  
  17. ans=0
  18.  
  19. for j in range(n):
  20. p1= k + arr[j]
  21. p2= -1*k + arr[j]
  22.  
  23. if p1 in hm:
  24. i=hm[p1]
  25. s= ps[j] if i==0 else ps[j]-ps[i-1]
  26. ans=max(ans,s)
  27.  
  28. if p2 in hm:
  29. i=hm[p2]
  30. s= ps[j] if i==0 else ps[j]-ps[i-1]
  31. ans=max(ans,s)
  32.  
  33. if arr[j] not in hm:
  34. hm[arr[j]]=j
  35. else:
  36. prevIndexPS=ps[hm[arr[j]]]
  37. currIndexPS=ps[j]
  38. if currIndexPS < prevIndexPS:
  39. hm[arr[j]]=j
  40.  
  41.  
  42. return ans
  43.  
  44.  
  45. print(main([1,5,-5,8,8,8,10,15],5))
Success #stdin #stdout 0.1s 14200KB
stdin
Standard input is empty
stdout
34