Maximum Sum Obtained of Any Permutation - Line Sweep w/ Prefix Sum [JS]

Description 

Solution: Line Sweep w/ Prefix Sum

  1. Count the number of requests for each index in nums using line sweep and prefix sum.
  2. Filter out the indexes with at least 1 request and sort them in desc order based on the number of requests.
  3. Sort nums in desc order.
  4. Assign each number (from largest to smallest) to the sorted indexes.

n = length of numsm = number of requests
Time Complexity: O(n log(n) + m) 609ms
Space Complexity: O(n) 80.8MB

var maxSumRangeQuery = function(nums, requests) {
  let n = nums.length, sum = Array(n).fill(0);
  for (let [start, end] of requests) {
    sum[start]++;
    sum[end + 1]--;
  }
  for (let i = 1; i < n; i++) {
    sum[i] += sum[i - 1];
  }

  let indexes = sum.filter((num) => num > 0).sort((a, b) => b - a);
  nums.sort((a, b) => b - a);
  let ans = 0, MOD = 10 ** 9 + 7;
  for (let i = 0, j = 0; i < indexes.length; i++) {
    ans = (ans + indexes[i] * nums[j]) % MOD;
    j++;
  }
  return ans;
};

Comments

Popular posts from this blog

Beautiful Towers II - Monotonic Increasing Stack [JS]

Minimum Number of Operations to Sort a Binary Tree by Level - BFS & Cycle Counting Explained [JS]

Maximum Sum of Distinct Subarrays With Length K - Sliding Window w/ Two Pointers & Set [JS]

Maximum Score After Applying Operations on a Tree - DFS [JS]

Divide Nodes Into the Maximum Number of Groups - Union Find & BFS [JS]