LeetCode 2542: Maximum Subsequence Score

Problem Description

Explanation

To solve this problem, we can iterate over all possible subsequences of length k from nums1. For each subsequence, we calculate the score as mentioned in the problem description and keep track of the maximum score obtained. We can do this efficiently by sorting nums1 and nums2 in non-decreasing order and then selecting the largest elements from both arrays.

  • Sort nums1 and nums2 in non-decreasing order.
  • Initialize a variable maxScore to keep track of the maximum score.
  • Iterate over all subsequences of length k from nums1.
  • For each subsequence, calculate the score using the formula provided.
  • Update maxScore if the current score is greater.
  • Return maxScore as the final answer.

Time Complexity

The time complexity of this approach is O(n log n) due to sorting nums1 and nums2. The iteration over all subsequences is O(n choose k) which is bounded by O(n^k) in the worst case.

Space Complexity

The space complexity is O(n) due to the sorting of the input arrays and the additional space used for variables.

Solutions

import java.util.Arrays;

class Solution {
    public int maxScore(int[] nums1, int[] nums2, int k) {
        int n = nums1.length;
        Arrays.sort(nums1);
        Arrays.sort(nums2);
        int maxScore = 0;

        for (int i = 0; i < k; i++) {
            int score = (nums1[n - k + i] + nums1[i]) * Math.min(nums2[n - k + i], nums2[i]);
            maxScore = Math.max(maxScore, score);
        }

        return maxScore;
    }
}

Loading editor...