Skip to content

1589. Maximum Sum Obtained of Any Permutation 👍

  • Time: $O(n + |\texttt{requests}|)$
  • Space: $O(n)$
 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
class Solution {
 public:
  int maxSumRangeQuery(vector<int>& nums, vector<vector<int>>& requests) {
    constexpr int kMod = 1'000'000'007;
    long ans = 0;
    // count[i] := the number of times nums[i] has been requested
    vector<int> count(nums.size());

    for (const vector<int>& request : requests) {
      const int start = request[0];
      const int end = request[1];
      ++count[start];
      if (end + 1 < nums.size())
        --count[end + 1];
    }

    for (int i = 1; i < nums.size(); ++i)
      count[i] += count[i - 1];

    ranges::sort(count);
    ranges::sort(nums);

    for (int i = 0; i < nums.size(); ++i) {
      ans += static_cast<long>(nums[i]) * count[i];
      ans %= kMod;
    }

    return ans;
  }
};
 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
class Solution {
  public int maxSumRangeQuery(int[] nums, int[][] requests) {
    final int kMod = 1_000_000_007;
    long ans = 0;
    // count[i] := the number of times nums[i] has been requested
    int[] count = new int[nums.length];

    for (int[] request : requests) {
      final int start = request[0];
      final int end = request[1];
      ++count[start];
      if (end + 1 < nums.length)
        --count[end + 1];
    }

    for (int i = 1; i < nums.length; ++i)
      count[i] += count[i - 1];

    Arrays.sort(count);
    Arrays.sort(nums);

    for (int i = 0; i < nums.length; ++i) {
      ans += (long) nums[i] * count[i];
      ans %= kMod;
    }

    return (int) ans;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
class Solution:
  def maxSumRangeQuery(self, nums: list[int], requests: list[list[int]]) -> int:
    kMod = 1_000_000_007
    ans = 0
    # count[i] := the number of times nums[i] has been requested
    count = [0] * len(nums)

    for start, end in requests:
      count[start] += 1
      if end + 1 < len(nums):
        count[end + 1] -= 1

    for i in range(1, len(nums)):
      count[i] += count[i - 1]

    for num, c in zip(sorted(nums), sorted(count)):
      ans += num * c
      ans %= kMod

    return ans