-
Notifications
You must be signed in to change notification settings - Fork 79
/
MaximumSubarraySum.py
52 lines (38 loc) · 1.13 KB
/
MaximumSubarraySum.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
#!/bin/python3
import math
import os
import random
import re
import sys
from bisect import insort, bisect_right
def maximumSum(a, m):
# Create prefix tree
prefix = [0] * len(a)
curr = 0
for i in range(len(a)):
curr = (a[i] % m + curr) % m
prefix[i] = curr
# Compute max modsum
pq = [prefix[0]]
maxmodsum = max(prefix)
for i in range(1, len(a)):
# Find cheapest prefix larger than prefix[i]
left = bisect_right(pq, prefix[i])
if left != len(pq):
# Update maxmodsum if possible
modsum = (prefix[i] - pq[left] + m) % m
maxmodsum = max(maxmodsum, modsum)
# add current prefix to heap
insort(pq, prefix[i])
return maxmodsum
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
q = int(input())
for q_itr in range(q):
nm = input().split()
n = int(nm[0])
m = int(nm[1])
a = list(map(int, input().rstrip().split()))
result = maximumSum(a, m)
fptr.write(str(result) + '\n')
fptr.close()