forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmaximum-sum-obtained-of-any-permutation.py
49 lines (43 loc) · 1.29 KB
/
maximum-sum-obtained-of-any-permutation.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
# Time: O(nlogn)
# Space: O(n)
import itertools
class Solution(object):
def maxSumRangeQuery(self, nums, requests):
"""
:type nums: List[int]
:type requests: List[List[int]]
:rtype: int
"""
def addmod(a, b, mod): # avoid overflow in other languages
a %= mod
b %= mod
if mod-a <= b:
b -= mod
return a+b
def mulmod(a, b, mod): # avoid overflow in other languages
a %= mod
b %= mod
if a < b:
a, b = b, a
result = 0
while b > 0:
if b%2 == 1:
result = addmod(result, a, mod)
a = addmod(a, a, mod)
b //= 2
return result
MOD = 10**9+7
count = [0]*len(nums)
for start, end in requests:
count[start] += 1
if end+1 < len(count):
count[end+1] -= 1
for i in xrange(1, len(count)):
count[i] += count[i-1]
nums.sort()
count.sort()
result = 0
for i, (num, c) in enumerate(itertools.izip(nums, count)):
# result = addmod(result, mulmod(num, c, MOD), MOD)
result = (result+num*c)%MOD
return result