Skip to content

Commit 64d805f

Browse files
authored
Create maximum-sum-obtained-of-any-permutation.py
1 parent 091ae0b commit 64d805f

File tree

1 file changed

+49
-0
lines changed

1 file changed

+49
-0
lines changed
Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
# Time: O(nlogn)
2+
# Space: O(n)
3+
4+
import itertools
5+
6+
7+
class Solution(object):
8+
def maxSumRangeQuery(self, nums, requests):
9+
"""
10+
:type nums: List[int]
11+
:type requests: List[List[int]]
12+
:rtype: int
13+
"""
14+
def addmod(a, b, mod): # avoid overflow in other languages
15+
a %= mod
16+
b %= mod
17+
if mod-a <= b:
18+
b -= mod
19+
return a+b
20+
21+
def mulmod(a, b, mod): # avoid overflow in other languages
22+
a %= mod
23+
b %= mod
24+
if a < b:
25+
a, b = b, a
26+
result = 0
27+
while b > 0:
28+
if b%2 == 1:
29+
result = addmod(result, a, mod)
30+
a = addmod(a, a, mod)
31+
b //= 2
32+
return result
33+
34+
MOD = 10**9+7
35+
36+
count = [0]*len(nums)
37+
for start, end in requests:
38+
count[start] += 1
39+
if end+1 < len(count):
40+
count[end+1] -= 1
41+
for i in xrange(1, len(count)):
42+
count[i] += count[i-1]
43+
nums.sort()
44+
count.sort()
45+
result = 0
46+
for i, (num, c) in enumerate(itertools.izip(nums, count)):
47+
# result = addmod(result, mulmod(num, c, MOD), MOD)
48+
result = (result+num*c)%MOD
49+
return result

0 commit comments

Comments
 (0)