Similar Problems

Similar Problems not available

Minimum Operations To Make A Subsequence - Leetcode Solution

Companies:

LeetCode:  Minimum Operations To Make A Subsequence Leetcode Solution

Difficulty: Hard

Topics: greedy hash-table binary-search array  

Problem Statement:

Given two integer arrays nums1 and nums2, return the length of the longest subsequence that appears in both arrays.

A subsequence is a sequence that can be derived from another sequence by deleting some or no elements without changing the order of the remaining elements.

Constraints: 1 <= nums1.length, nums2.length <= 1000 0 <= nums1[i], nums2[i] <= 2000

Example:

Input: nums1 = [1,3,5,6,7], nums2 = [1,2,3,4,5,6]

Output: 4

Explanation:

The longest subsequence is [1,3,5,6] or [1,2,3,6] or [1,2,3,4,5,6], all of which have a length of 4.

Solution:

The given problem can be solved using dynamic programming. The subproblem can be defined as follows: Let dp[i][j] denote the length of the longest common subsequence that can be formed from the given two arrays up to the i-th element of nums1 and the j-th element of nums2.

The base cases are dp[0][j] = 0 and dp[i][0] = 0, as there cannot be any common subsequence between an empty array and any other array.

If nums1[i] == nums2[j], then dp[i][j] = 1 + dp[i-1][j-1], as the current element can be added to the longest common subsequence formed till the i-1th element of nums1 and j-1th element of nums2.

Otherwise, dp[i][j] = max(dp[i-1][j], dp[i][j-1]), as there can be two possibilities to form the longest common subsequence i.e., either by removing the i-th element of nums1 or by removing the j-th element of nums2.

At the end, dp[nums1.length][nums2.length] will give the length of the longest common subsequence that can be formed from the given two arrays.

Implementation:

public int minOperations(int[] nums1, int[] nums2) {

int n1 = nums1.length;
int n2 = nums2.length;

if (n1 * 6 < n2 || n2 * 6 < n1) {
    return -1;
}

int[] freq1 = new int[7];
int[] freq2 = new int[7];

int diff = 0;

for (int num : nums1) {
    freq1[num]++;
    diff += num;
}

for (int num : nums2) {
    freq2[num]++;
    diff -= num;
}

if (diff > 0) {
    freq1 = freq2;
    freq2 = freq1;
    diff = -diff;
}

int count = 0;

for (int i = 1; i <= 6; i++) {
    int j = 7 - i;
    while (freq1[i] > 0 && diff > 0 || freq2[j] > 0 && diff > 0) {
        if (freq1[i] > 0) {
            freq1[i]--;
            diff -= 6 - i;
        } else {
            freq2[j]--;
            diff -= j - 1;
        }
        count++;
    }
}

return count;

}

Minimum Operations To Make A Subsequence Solution Code

1