LeetCode Solutions
646. Maximum Length of Pair Chain
Time: $O(n\log n)$ Space: $O(1)$
class Solution {
public:
int findLongestChain(vector<vector<int>>& pairs) {
int ans = 0;
int prevEnd = INT_MIN;
sort(begin(pairs), end(pairs),
[](const auto& a, const auto& b) { return a[1] < b[1]; });
for (const vector<int>& pair : pairs)
if (pair[0] > prevEnd) {
++ans;
prevEnd = pair[1];
}
return ans;
}
};
import java.util.Arrays;
class Solution {
public int findLongestChain(int[][] pairs) {
int ans = 0;
int prevEnd = Integer.MIN_VALUE;
Arrays.sort(pairs, (a, b) -> a[1] - b[1]);
for (int[] pair : pairs)
if (pair[0] > prevEnd) {
++ans;
prevEnd = pair[1];
}
return ans;
}
}
class Solution:
def findLongestChain(self, pairs: List[List[int]]) -> int:
ans = 0
prevEnd = -math.inf
for s, e in sorted(pairs, key=lambda x: x[1]):
if s > prevEnd:
ans += 1
prevEnd = e
return ans