#3836

Maximum Score Using Exactly K Pairs

Hard
ArrayDynamic ProgrammingDynamic ProgrammingGreedy Algorithms
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n * m * k)
Space
O(n²)
O(k)
💡

Intuition

Time O(n * m * k)Space O(k)

Use dynamic programming to maintain the maximum score achievable with k pairs by iterating through the arrays and selecting optimal pairs based on previous results.

⚙️

Algorithm

3 steps
  1. 1Step 1: Initialize a DP array where dp[k] keeps track of the maximum score achievable with k pairs.
  2. 2Step 2: Iterate through nums1 and nums2, updating the DP array based on the current element's contribution to the score.
  3. 3Step 3: Return dp[k] as the maximum score using exactly k pairs.
solution.py8 lines
1def maxScore(nums1, nums2, k):
2    n, m = len(nums1), len(nums2)
3    dp = [0] * (k + 1)
4    for i in range(n):
5        for j in range(m):
6            for x in range(k, 0, -1):
7                dp[x] = max(dp[x], dp[x - 1] + nums1[i] * nums2[j])
8    return dp[k]

Complexity note: The time complexity arises from the nested loops iterating through nums1, nums2, and k pairs.

  • 1Choosing larger values from both arrays maximizes score.
  • 2Maintaining order in indices is crucial.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.