K Pairs Multiplication
You are given two arrays of integers, nums1 and nums2, alongside a target integer k. Your task is to form exactly k pairs of numbers, where each pair consists of one number from nums1 and one number from nums2.
The catch is that you must maintain the original relative order. If you pick a pair early in the arrays, you cannot go backward to pick elements you skipped. Every time you form a pair, you multiply the two numbers together. You want to maximize the total sum of these k products.
Find the highest possible score by pairing elements without violating their left-to-right order.
Example 1:
Input: nums1 = [5, 2, -1], nums2 = [1, 3, -4, 2], k = 2
Output: 19
Explanation: To maximize the score using exactly 2 pairs, we can select the index pair (0, 1) and the index pair (2, 2). The first pair multiplies nums1[0] and nums2[1] to get 5 * 3 = 15. The second pair multiplies nums1[2] and nums2[2] to get -1 * -4 = 4. Because the chosen indices are strictly increasing for both arrays (0 < 2 and 1 < 2), this is a valid selection. The maximum achievable total score is 15 + 4 = 19.
Example 2:
Input: nums1 = [-1, -2, -3], nums2 = [-5, -4, -3], k = 3
Output: 22
Explanation: Since k is 3 and both arrays have a length of 3, we are forced to pair every element exactly in its original order to maintain the strictly increasing indices rule. We pair (0, 0) for a score of -1 * -5 = 5. Next, we pair (1, 1) for a score of -2 * -4 = 8. Finally, we pair (2, 2) for a score of -3 * -3 = 9. Adding these individual products together yields our final maximum score of 5 + 8 + 9 = 22.
Now Your Turn!
Pick the correct output for the given inputInput: nums1 = [4, 1, 5, 3], nums2 = [2, 6, 1], k = 2
Still unsure what the problem is asking ?
Let’s go through a few more examples, step by step, to make it clearer.
Constraints:
- 1 <= n == nums1.length <= 100
- 1 <= m == nums2.length <= 100
- -106 <= nums1[i], nums2[i] <= 106
- 1 <= k <= min(n, m)