Maximum Subsequence Score

Choose k indexes so that the sum of their nums1 values times their smallest nums2 value is as large as possible.

Given two integer arrays nums1 and nums2 of the same length n, and a number k, choose k different indexes. The score of a choice is the sum of the nums1 values at those indexes, multiplied by the smallest nums2 value at those indexes. Return the largest score that any choice of k indexes can reach.

Example 1
Input: nums1 = [1, 3, 3, 2], nums2 = [2, 1, 3, 4], k = 3
Output: 12
Explanation: indexes 0, 2 and 3 give (1 + 3 + 2) × min(2, 3, 4) = 6 × 2 = 12.
Example 2
Input: nums1 = [4, 2, 3, 1, 1], nums2 = [7, 5, 10, 9, 6], k = 1
Output: 30
Explanation: index 2 alone gives 3 × 10 = 30.
Solution

The Idea

Think of a convoy of trucks. Each truck carries some cargo and has its own top speed, but the trucks drive together, so the convoy moves at the speed of its slowest truck. The cargo delivered per hour is the total cargo times that slowest speed. In this problem, nums1[i] is the cargo of truck i, nums2[i] is its speed, and you send out k trucks.

Take Example 1, where 3 of the 4 indexes must be chosen. There are four choices. Indexes 0, 1, 2 give 7 × 1 = 7, and indexes 0, 1, 3 give 6 × 1 = 6. Indexes 1, 2, 3 give 8 × 1 = 8, and indexes 0, 2, 3 give 6 × 2 = 12. Index 1 carries 3, one of the largest loads, but its speed of 1 pulls every choice that includes it down to a multiplier of 1.

So the two parts of the score pull against each other: a big nums1 value may come with a small nums2 value. With 4 indexes, trying all four choices is quick, but the number of choices grows very fast as the arrays get longer. Can we deal with one part of the score at a time?

We can, by deciding first which index is the slowest one in the choice. Say it is index 0, with nums2 = 2. Then the other two indexes may only come from those whose nums2 is at least 2, which are indexes 2 and 3. The multiplier is now fixed at 2, so the best we can do is take the largest nums1 values among the allowed indexes.

Trying every index as the slowest one becomes easy when the indexes are visited in order of nums2, largest first: 3, 2, 0, 1. Each index reached has a nums2 value no larger than any index before it, so every index already visited is an allowed partner. Along the way, we keep the 3 largest nums1 values met so far. A min-heap, a structure that always hands back its smallest value first, holds them, so the smallest one can be dropped quickly when a fourth value arrives.

Look at the picture below. Each row is one index reached, in that order.

Example 1 with k = 3, indexes visited in order of nums2 from largest to smallest: 3, 2, 0, 1. At index 0 the kept nums1 values are 1, 2, 3 and the score is 6 × 2 = 12. At index 1 the value 1 is dropped, the sum becomes 8 and the score 8 × 1 = 8.

In the rows labelled index 3 and index 2, fewer than 3 values are kept, so there is no score yet. In the row labelled index 0, the kept values are 1, 2 and 3, their sum is 6, and the score is 6 × 2 = 12. In the last row, index 1 brings a 3, the heap would hold four values, and the smallest, 1, is dropped. The sum becomes 8, but the speed falls to 1, so the score is only 8 × 1 = 8. The best score seen is 12, the answer.

So the sorted order settles the smallest nums2 value, and the min-heap settles the largest sum that goes with it.

Solution Approach

Turning that idea into code means settling four things: the order in which to visit the indexes, how to keep the k largest nums1 values, when a score counts, and how large a score can get. A look at the slow way first shows what the sorted order saves.

Trying every choice

Why not simply try every choice of k indexes? Example 1 has only four choices, but 100 indexes with k = 50 have about 1029, and each one needs its own sum and smallest value. The sorted walk instead looks at each index once.

Visiting the indexes by nums2

What exactly gets sorted? Not nums2 itself, because the nums1 and nums2 values at the same index must stay together. Sort an array of the indexes 0 to n - 1 instead, comparing them by their nums2 values, largest first. Equal nums2 values cause no trouble: an index reached later still has a value no larger than any index before it.

Keeping the k largest nums1 values

How do we keep the k largest values while new ones keep arriving? Each new nums1 value goes into the min-heap and is added to a running sum. When the heap grows to k + 1 values, the smallest one is taken out and subtracted from the sum. Java's PriorityQueue class is a heap, and with the comparator (a, b) -> Integer.compare(a, b) it keeps the smallest value on top, so it works as a min-heap.

When a score counts

A score is computed only when the heap holds exactly k values, since a choice needs k indexes. Then the sum times the nums2 value of the index just reached is a candidate for the answer.

What if the index just reached is the one whose value was dropped? Then every kept index has a nums2 value at least as large as the nums2 value of the index just reached, so the real score of the kept indexes is at least the computed one. The computed score can be too low, but never too high. It also cannot miss the best choice. When that choice's slowest index is reached (the last one, if several tie), all its indexes have been visited, so the kept sum is at least as large as its sum.

How large a score can get

Can the score outgrow an int? An int stops at about 2.1 billion. Three indexes with nums1 and nums2 values of 100,000 have a sum of 300,000 and a score of 30,000,000,000. Keeping the sum and the best score as long makes Java compute the product in long too.

Java Solution

The method maxScore works in these steps:

  1. First, build an array order holding the indexes 0 to n - 1, as Integer values so it can be sorted with a comparator. Sort it by nums2, largest first, with Arrays.sort(order, (a, b) -> Integer.compare(nums2[b], nums2[a])).
  2. Create the min-heap kept, a PriorityQueue of the kept nums1 values, and two long variables that start at 0: sum for the kept values and best for the best score so far.
  3. Loop over order with i. Add nums1[i] to kept and to sum. If kept now holds more than k values, take out its smallest with kept.poll() and subtract it from sum.
  4. When kept holds exactly k values, compute sum * nums2[i] and keep it in best if it is larger.
  5. After the last index, best holds the largest score, and the method returns it.

The main method runs both examples, Example 1 again with k = 4, a case where the last index reached is dropped at once, and three indexes of 100,000 whose score needs a long.

Java
import java.util.Arrays;
import java.util.PriorityQueue;

public class MaximumSubsequenceScore {

    public static long maxScore(int[] nums1, int[] nums2, int k) {
        int n = nums1.length;
        Integer[] order = new Integer[n];
        for (int i = 0; i < n; i++) {
            order[i] = i;
        }
        Arrays.sort(order, (a, b) -> Integer.compare(nums2[b], nums2[a]));  // nums2, largest first

        // min-heap: the smallest kept nums1 value is on top
        PriorityQueue<Integer> kept = new PriorityQueue<>((a, b) -> Integer.compare(a, b));
        long sum = 0;
        long best = 0;
        for (int i : order) {
            kept.add(nums1[i]);
            sum += nums1[i];
            if (kept.size() > k) {
                sum -= kept.poll();               // drop the smallest kept nums1 value
            }
            if (kept.size() == k) {
                // nums2[i] is the smallest nums2 met so far
                best = Math.max(best, sum * nums2[i]);
            }
        }
        return best;
    }

    public static void main(String[] args) {
        System.out.println(maxScore(new int[] {1, 3, 3, 2}, new int[] {2, 1, 3, 4}, 3));
        System.out.println(maxScore(new int[] {4, 2, 3, 1, 1}, new int[] {7, 5, 10, 9, 6}, 1));
        System.out.println(maxScore(new int[] {1, 3, 3, 2}, new int[] {2, 1, 3, 4}, 4));
        System.out.println(maxScore(new int[] {5, 5, 1}, new int[] {3, 3, 2}, 2));
        int big = 100000;
        System.out.println(maxScore(new int[] {big, big, big}, new int[] {big, big, big}, 3));
    }
}

Running it prints:

Output
12
30
9
30
30000000000

The answers 12 and 30 match the two examples. The 9 below them is Example 1 with k = 4. Every index must be chosen, so the score is (1 + 3 + 3 + 2) × 1 = 9, held down by the speed of index 1.

The second 30 comes from nums1 = [5, 5, 1] and nums2 = [3, 3, 2] with k = 2. Indexes 0 and 1 score 10 × 3 = 30. When index 2 is reached, its 1 goes into the heap and straight back out, and the computed score is 10 × 2 = 20, lower than the real 30. best already holds 30, so the low score does no harm.

Look at the last line, 30000000000. With sum declared as int, the product 300,000 × 100,000 is computed in int and wraps around to -64,771,072. That version never finds a positive score for this input and returns 0.

Complexity

The work is the sort of the indexes, plus one heap step or two for each index.

  • Time: O(n log n), because sorting the n indexes by nums2 costs O(n log n), and then each index makes one add and at most one poll, each O(log k) on a heap of at most k + 1 values.
  • Space: O(n), because the order array holds all n indexes, while the heap never holds more than k + 1 values.

Visiting items in order of one value while a heap keeps the best of another also solves Minimum Cost to Hire K Workers.