Maximum Score Using Exactly K Pairs Problem
Description
LeetCode Problem 3836.
You are given two integer arrays nums1 and nums2 of lengths n and m respectively, and an integer k.
You must choose exactly k pairs of indices (i_1, j_1), (i_2, j_2), ..., (i_k, j_k) such that:
0 <= i_1 < i_2 < ... < i_k < n0 <= j_1 < j_2 < ... < j_k < m
For each chosen pair (i, j), you gain a score of nums1[i] * nums2[j].
The total score is the sum of the products of all selected pairs.
Return an integer representing the maximum achievable total score.
Example 1:
Input: nums1 = [1,3,2], nums2 = [4,5,1], k = 2
Output: 22
Explanation:
One optimal choice of index pairs is:
- (i_1, j_1) = (1, 0) which scores 3 * 4 = 12
- (i_2, j_2) = (2, 1) which scores 2 * 5 = 10
This gives a total score of 12 + 10 = 22.
Example 2:
Input: nums1 = [-2,0,5], nums2 = [-3,4,-1,2], k = 2
Output: 26
Explanation:
One optimal choice of index pairs is:
- (i_1, j_1) = (0, 0) which scores -2 * -3 = 6
- (i_2, j_2) = (2, 1) which scores 5 * 4 = 20
The total score is 6 + 20 = 26.
Example 3:
Input: nums1 = [-3,-2], nums2 = [1,2], k = 2
Output: -7
Explanation:
The optimal choice of index pairs is:
- (i_1, j_1) = (0, 0) which scores -3 * 1 = -3
- (i_2, j_2) = (1, 1) which scores -2 * 2 = -4
The total score is -3 + (-4) = -7.
Constraints:
1 <= n == nums1.length <= 1001 <= m == nums2.length <= 100-10^6 <= nums1[i], nums2[i] <= 10^61 <= k <= min(n, m)
Solution
Approach: Dynamic Programming
Let f[i][j][t] be the maximum score when choosing exactly t pairs from the first i elements of nums1 and the first j elements of nums2. Start with f[0][0][0] = 0 and every other state as negative infinity (a very small number, such as -10^18, is enough since the real scores stay near 10^14).
Each state is reached in one of three ways:
- skip
nums1[i - 1]:f[i - 1][j][t], - skip
nums2[j - 1]:f[i][j - 1][t], - pair them:
f[i - 1][j - 1][t - 1] + nums1[i - 1] * nums2[j - 1].
Because the indices of the chosen pairs must increase in both arrays, pairing the last two elements of the prefixes is the only way to use them, and the first two options cover leaving them out. The answer is f[n][m][k]. Products reach 10^12 and sums 10^14, so use 64-bit integers.
Complexity:
- Time:
O(n * m * k). - Space:
O(n * m * k).
class Solution:
def maxScore(self, nums1: List[int], nums2: List[int], K: int) -> int:
n, m = len(nums1), len(nums2)
NEG = -(10**18)
f = [[[NEG] * (K + 1) for _ in range(m + 1)] for _ in range(n + 1)]
f[0][0][0] = 0
for i in range(n + 1):
for j in range(m + 1):
for k in range(K + 1):
if i > 0:
f[i][j][k] = max(f[i][j][k], f[i - 1][j][k])
if j > 0:
f[i][j][k] = max(f[i][j][k], f[i][j - 1][k])
if i > 0 and j > 0 and k > 0:
f[i][j][k] = max(
f[i][j][k],
f[i - 1][j - 1][k - 1] + nums1[i - 1] * nums2[j - 1],
)
return f[n][m][K]