返回介绍

solution / 2300-2399 / 2386.Find the K-Sum of an Array / README_EN

发布于 2024-06-17 01:03:06 字数 6144 浏览 0 评论 0 收藏 0

2386. Find the K-Sum of an Array

中文文档

Description

You are given an integer array nums and a positive integer k. You can choose any subsequence of the array and sum all of its elements together.

We define the K-Sum of the array as the kth largest subsequence sum that can be obtained (not necessarily distinct).

Return _the K-Sum of the array_.

A subsequence is an array that can be derived from another array by deleting some or no elements without changing the order of the remaining elements.

Note that the empty subsequence is considered to have a sum of 0.

 

Example 1:

Input: nums = [2,4,-2], k = 5
Output: 2
Explanation: All the possible subsequence sums that we can obtain are the following sorted in decreasing order:
- 6, 4, 4, 2, 2, 0, 0, -2.
The 5-Sum of the array is 2.

Example 2:

Input: nums = [1,-2,3,4,-10,12], k = 16
Output: 10
Explanation: The 16-Sum of the array is 10.

 

Constraints:

  • n == nums.length
  • 1 <= n <= 105
  • -109 <= nums[i] <= 109
  • 1 <= k <= min(2000, 2n)

Solutions

Solution 1: Priority Queue (Min Heap)

First, we find the maximum subsequence sum $mx$, which is the sum of all positive numbers.

It can be found that the sum of other subsequences can be regarded as the maximum subsequence sum, minus the sum of other part of the subsequence. Therefore, we can convert the problem into finding the $k$-th smallest subsequence sum.

We only need to sort all numbers in ascending order by their absolute values, then establish a min heap, storing pairs $(s, i)$, representing the current sum is $s$, and the index of the next number to be selected is $i$.

Each time we take out the top of the heap, and put in two new situations: one is to select the next position, and the other is to select the next position and not select this position.

Since the array is sorted from small to large, this method can traverse all subsequence sums in order without duplication.

The time complexity is $O(n \times \log n + k \times \log k)$, where $n$ is the length of the array nums, and $k$ is the given $k$ in the problem.

class Solution:
  def kSum(self, nums: List[int], k: int) -> int:
    mx = 0
    for i, x in enumerate(nums):
      if x > 0:
        mx += x
      else:
        nums[i] = -x
    nums.sort()
    h = [(0, 0)]
    for _ in range(k - 1):
      s, i = heappop(h)
      if i < len(nums):
        heappush(h, (s + nums[i], i + 1))
        if i:
          heappush(h, (s + nums[i] - nums[i - 1], i + 1))
    return mx - h[0][0]
class Solution {
  public long kSum(int[] nums, int k) {
    long mx = 0;
    int n = nums.length;
    for (int i = 0; i < n; ++i) {
      if (nums[i] > 0) {
        mx += nums[i];
      } else {
        nums[i] *= -1;
      }
    }
    Arrays.sort(nums);
    PriorityQueue<Pair<Long, Integer>> pq
      = new PriorityQueue<>(Comparator.comparing(Pair::getKey));
    pq.offer(new Pair<>(0L, 0));
    while (--k > 0) {
      var p = pq.poll();
      long s = p.getKey();
      int i = p.getValue();
      if (i < n) {
        pq.offer(new Pair<>(s + nums[i], i + 1));
        if (i > 0) {
          pq.offer(new Pair<>(s + nums[i] - nums[i - 1], i + 1));
        }
      }
    }
    return mx - pq.peek().getKey();
  }
}
class Solution {
public:
  long long kSum(vector<int>& nums, int k) {
    long long mx = 0;
    int n = nums.size();
    for (int i = 0; i < n; ++i) {
      if (nums[i] > 0) {
        mx += nums[i];
      } else {
        nums[i] *= -1;
      }
    }
    sort(nums.begin(), nums.end());
    using pli = pair<long long, int>;
    priority_queue<pli, vector<pli>, greater<pli>> pq;
    pq.push({0, 0});
    while (--k) {
      auto p = pq.top();
      pq.pop();
      long long s = p.first;
      int i = p.second;
      if (i < n) {
        pq.push({s + nums[i], i + 1});
        if (i) {
          pq.push({s + nums[i] - nums[i - 1], i + 1});
        }
      }
    }
    return mx - pq.top().first;
  }
};
func kSum(nums []int, k int) int64 {
  mx := 0
  for i, x := range nums {
    if x > 0 {
      mx += x
    } else {
      nums[i] *= -1
    }
  }
  sort.Ints(nums)
  h := &hp{{0, 0}}
  for k > 1 {
    k--
    p := heap.Pop(h).(pair)
    if p.i < len(nums) {
      heap.Push(h, pair{p.sum + nums[p.i], p.i + 1})
      if p.i > 0 {
        heap.Push(h, pair{p.sum + nums[p.i] - nums[p.i-1], p.i + 1})
      }
    }
  }
  return int64(mx) - int64((*h)[0].sum)
}

type pair struct{ sum, i int }
type hp []pair

func (h hp) Len() int       { return len(h) }
func (h hp) Less(i, j int) bool { return h[i].sum < h[j].sum }
func (h hp) Swap(i, j int)    { h[i], h[j] = h[j], h[i] }
func (h *hp) Push(v any)    { *h = append(*h, v.(pair)) }
func (h *hp) Pop() any      { a := *h; v := a[len(a)-1]; *h = a[:len(a)-1]; return v }

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文