Getting everything ready for you…

Loading courses, problems and your progress. This takes just a moment.

0s

Practice › Heap & Priority Queue

Maximum Sum Combinations

Medium · Heap & Priority Queue · Asked at Amazon, Microsoft, Flipkart

Arrays A and B both have n elements (in any order). Among all n² sums A[i] + B[j], print the k largest, in non-increasing order.

Input

First line: n k. Second line: array A. Third line: array B.

Output

k sums, space-separated.

Constraints

Sort both arrays in decreasing order. The largest sum is A[0] + B[0]. Use a max-heap of (sum, i, j) with a set of visited pairs; each time you pop (i, j), push (i + 1, j) and (i, j + 1) if not seen. k pops give the answer.

Example 1

Input

2 2
3 2
1 4

Output

7 6

Example 2

Input

4 3
1 4 2 3
2 5 1 6

Output

10 9 9

Hints

  1. Sort both arrays in decreasing order; the largest sum is A[0] + B[0].
  2. The next candidates after (i, j) are (i + 1, j) and (i, j + 1).
  3. A max-heap plus a visited set explores pairs in decreasing order of sum.

Approach

Push (A[0] + B[0], 0, 0). Repeat k times: pop the largest sum and output it, then push (i + 1, j) and (i, j + 1) if they are inside the arrays and not visited yet. Every sum not yet output is reachable from a popped pair through these moves, so the heap always holds the next largest one. Each pop adds at most two entries, so the work is O(k log k) after sorting.

Complexity: O(n log n + k log k) time · O(n + k) space

Solution

C++ solution

#include <bits/stdc++.h>
using namespace std;

int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    int n, k;
    cin >> n >> k;
    vector<long long> a(n), b(n);
    for (auto &x : a) cin >> x;
    for (auto &x : b) cin >> x;
    sort(a.rbegin(), a.rend());
    sort(b.rbegin(), b.rend());
    priority_queue<tuple<long long, int, int>> pq;
    set<pair<int, int>> seen;
    pq.push(make_tuple(a[0] + b[0], 0, 0));
    seen.insert({0, 0});
    string out;
    for (int c = 0; c < k; c++) {
        tuple<long long, int, int> t = pq.top();
        pq.pop();
        long long s = get<0>(t);
        int i = get<1>(t), j = get<2>(t);
        out += (c ? " " : "") + to_string(s);
        if (i + 1 < n && seen.insert({i + 1, j}).second) pq.push(make_tuple(a[i + 1] + b[j], i + 1, j));
        if (j + 1 < n && seen.insert({i, j + 1}).second) pq.push(make_tuple(a[i] + b[j + 1], i, j + 1));
    }
    cout << out << "\n";
    return 0;
}

Python solution

import heapq
import sys

data = list(map(int, sys.stdin.read().split()))
n, k = data[0], data[1]
a = sorted(data[2 : 2 + n], reverse=True)
b = sorted(data[2 + n : 2 + 2 * n], reverse=True)
heap = [(-(a[0] + b[0]), 0, 0)]
seen = {(0, 0)}
out = []
for _ in range(k):
    s, i, j = heapq.heappop(heap)
    out.append(-s)
    if i + 1 < n and (i + 1, j) not in seen:
        seen.add((i + 1, j))
        heapq.heappush(heap, (-(a[i + 1] + b[j]), i + 1, j))
    if j + 1 < n and (i, j + 1) not in seen:
        seen.add((i, j + 1))
        heapq.heappush(heap, (-(a[i] + b[j + 1]), i, j + 1))
print(*out)

Java solution

import java.io.*;
import java.util.*;

public class Main {
    public static void main(String[] args) throws IOException {
        StreamTokenizer in = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));
        in.nextToken();
        int n = (int) in.nval;
        in.nextToken();
        int k = (int) in.nval;
        Long[] a = new Long[n], b = new Long[n];
        for (int i = 0; i < n; i++) {
            in.nextToken();
            a[i] = (long) in.nval;
        }
        for (int i = 0; i < n; i++) {
            in.nextToken();
            b[i] = (long) in.nval;
        }
        Arrays.sort(a, Collections.reverseOrder());
        Arrays.sort(b, Collections.reverseOrder());
        PriorityQueue<long[]> pq = new PriorityQueue<>((x, y) -> Long.compare(y[0], x[0]));
        HashSet<Long> seen = new HashSet<>();
        pq.add(new long[] {a[0] + b[0], 0, 0});
        seen.add(0L);
        StringBuilder sb = new StringBuilder();
        for (int c = 0; c < k; c++) {
            long[] t = pq.poll();
            int i = (int) t[1], j = (int) t[2];
            if (c > 0) sb.append(' ');
            sb.append(t[0]);
            if (i + 1 < n && seen.add((long) (i + 1) * n + j)) pq.add(new long[] {a[i + 1] + b[j], i + 1, j});
            if (j + 1 < n && seen.add((long) i * n + j + 1)) pq.add(new long[] {a[i] + b[j + 1], i, j + 1});
        }
        System.out.println(sb);
    }
}

Solve Maximum Sum Combinations online · All practice problems