Longest Subsequence With Limited Sum - Greedy - Sorting & Two Pointers [JS]

Description 

Solution: Greedy - Sorting & Two Pointers

It is always optimal to take the smallest numbers possible, since we want the more quantity.
Sort nums in asc order.
Sort queries in asc order and use two pointers (i = index in numsj = index in queries) to process the queries efficiently.
Move i up until it exceeds queries[j].

n = length of numsm = length of queries
Time Complexity: O(n log(n) + m log(m))
Space Complexity: O(m)

var answerQueries = function(nums, queries) {
  nums.sort((a, b) => a - b);
  queries = queries.map((query, idx) => [query, idx]).sort((a, b) => a[0] - b[0]);
  let n = nums.length, m = queries.length;
  let res = Array(m).fill(0);
  let sum = 0;
  for (let j = 0, i = 0; j < m; j++) {
    let [maxSum, index] = queries[j];
    while (i < n && sum + nums[i] <= maxSum) {
      sum += nums[i++];
    }
    res[index] = i;
  }
  return res;
};

Comments

Popular posts from this blog

Maximum Value of an Ordered Triplet II - Two Solutions [JS]

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

Sum of Prefix Scores of Strings - Trie [JS]

Maximum Count of Positive Integer and Negative Integer - Binary Search [JS]

Count Subarrays With Median K - Count Left & Right Balance [JS]