Skip to content

Comments

[646] Maximum Length of Pair Chain#652

Open
dlek-user wants to merge 1 commit intomainfrom
dlek-user-573
Open

[646] Maximum Length of Pair Chain#652
dlek-user wants to merge 1 commit intomainfrom
dlek-user-573

Conversation

@dlek-user
Copy link
Collaborator

[646] Maximum Length of Pair Chain

문제 설명

You are given an array of n pairs pairs where pairs[i] = [lefti, righti] and lefti < righti.

A pair p2 = [c, d] follows a pair p1 = [a, b] if b < c. A chain of pairs can be formed in this fashion.

Return the length longest chain which can be formed.

You do not need to use up all the given intervals. You can select pairs in any order.

Example 1:

Input: pairs = [[1,2],[2,3],[3,4]]
Output: 2
Explanation: The longest chain is [1,2] -> [3,4].

Example 2:

Input: pairs = [[1,2],[7,8],[4,5]]
Output: 3
Explanation: The longest chain is [1,2] -> [4,5] -> [7,8].

코드 설명

class Solution {
    public int findLongestChain(int[][] pairs) {
        Arrays.sort(pairs, (a, b) -> a[1] - b[1]);

        int count = 0;        
        int currentEnd = Integer.MIN_VALUE;  

        for (int[] pair : pairs) {

            if (pair[0] > currentEnd) {
                count++;              
                currentEnd = pair[1];  
            }
        }

        return count;
    }
}

Arrays.sort(pairs, (a, b) -> a[1] - b[1]);

우리는 가능한 한 빨리 끝나는 구간을 먼저 선택해야
→ 이후 더 많은 구간을 붙일 수 있음

int count = 0;

체인의 길이

int currentEnd = Integer.MIN_VALUE;

마지막으로 선택된 pair의 끝 값
처음엔 어떤 값도 선택하지 않았으므로
가장 작은 값으로 설정

for (int[] pair : pairs)

정렬된 배열을 순차 탐색

if (pair[0] > currentEnd)

이전 pair의 끝 < 현재 pair의 시작

count++;

체인 길이 증가

currentEnd = pair[1];

새로 선택한 pair의 끝값으로 갱신

return count;

최종 체인 길이 반환

[646] Maximum Length of Pair Chain
@dlek-user dlek-user added the coding test 코딩테스트 라벨 label Feb 22, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

coding test 코딩테스트 라벨

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant