P.S./leetcode

[Java] 1035. Uncrossed Lines - LeetCode Daily Challenge / Dynamic Programing(DP)

mag1c 2023. 5. 12. 06:57
728x90
728x90
 

Uncrossed Lines - LeetCode

Can you solve this real interview question? Uncrossed Lines - You are given two integer arrays nums1 and nums2. We write the integers of nums1 and nums2 (in the order they are given) on two separate horizontal lines. We may draw connecting lines: a straigh

leetcode.com

 

 

 

풀이


DP배열의 idx의 값은 해당 idx까지 서로 탐색을했을때, 겹치지 않는 최대 경우의 수를 나타낸다.

class Solution {
    public int maxUncrossedLines(int[] nums1, int[] nums2) {
        int n = nums1.length;
        int m = nums2.length;

        int[] dp = new int[m+1];
        for (int i=1; i<=n; i++) {
        	int prev = 0;
            for (int j=1; j<=m; j++) {
                int curr = dp[j];
                if (nums1[i-1] == nums2[j-1]) {
                    dp[j] = prev + 1;
                } else {
                    dp[j] = Math.max(dp[j-1], curr);
                }
                prev = curr;
            }
        }
        return dp[m];
    }
}

 

 

 

728x90
300x250