-
Notifications
You must be signed in to change notification settings - Fork 29
/
Copy path1589.maximum-sum-obtained-of-any-permutation.kt
81 lines (78 loc) · 2.23 KB
/
1589.maximum-sum-obtained-of-any-permutation.kt
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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
//We have an array of integers, nums, and an array of requests where requests[i]
// = [starti, endi]. The ith request asks for the sum of nums[starti] + nums[start
//i + 1] + ... + nums[endi - 1] + nums[endi]. Both starti and endi are 0-indexed.
//
//
// Return the maximum total sum of all requests among all permutations of nums.
//
//
// Since the answer may be too large, return it modulo 109 + 7.
//
//
// Example 1:
//
//
//Input: nums = [1,2,3,4,5], requests = [[1,3],[0,1]]
//Output: 19
//Explanation: One permutation of nums is [2,1,3,4,5] with the following result:
//
//requests[0] -> nums[1] + nums[2] + nums[3] = 1 + 3 + 4 = 8
//requests[1] -> nums[0] + nums[1] = 2 + 1 = 3
//Total sum: 8 + 3 = 11.
//A permutation with a higher total sum is [3,5,4,2,1] with the following result
//:
//requests[0] -> nums[1] + nums[2] + nums[3] = 5 + 4 + 2 = 11
//requests[1] -> nums[0] + nums[1] = 3 + 5 = 8
//Total sum: 11 + 8 = 19, which is the best that you can do.
//
//
// Example 2:
//
//
//Input: nums = [1,2,3,4,5,6], requests = [[0,1]]
//Output: 11
//Explanation: A permutation with the max total sum is [6,5,4,3,2,1] with reques
//t sums [11].
//
// Example 3:
//
//
//Input: nums = [1,2,3,4,5,10], requests = [[0,2],[1,3],[1,1]]
//Output: 47
//Explanation: A permutation with the max total sum is [4,10,5,3,2,1] with reque
//st sums [19,18,10].
//
//
// Constraints:
//
//
// n == nums.length
// 1 <= n <= 105
// 0 <= nums[i] <= 105
// 1 <= requests.length <= 105
// requests[i].length == 2
// 0 <= starti <= endi < n
//
// Related Topics Greedy
// 👍 182 👎 16
//leetcode submit region begin(Prohibit modification and deletion)
class Solution {
fun maxSumRangeQuery(nums: IntArray, requests: Array<IntArray>): Int {
val n = nums.size
val mod = 1000000007L
var count = IntArray(n)
for (r in requests) {
count[r[0]]++
if (r[1]+1 < n) {
count[r[1]+1]--
}
}
for (i in 1 until n) count[i] += count[i-1]
nums.sort()
count.sort()
var res = 0L
for (i in 0 until n) res = (res + nums[i].toLong() * count[i]) % mod
return res.toInt()
}
}
//leetcode submit region end(Prohibit modification and deletion)