Skip to content

Commit 6b26eba

Browse files
update 646
1 parent 3b9cbaf commit 6b26eba

File tree

1 file changed

+14
-14
lines changed
  • src/main/java/com/fishercoder/solutions/firstthousand

1 file changed

+14
-14
lines changed

Diff for: src/main/java/com/fishercoder/solutions/firstthousand/_646.java

+14-14
Original file line numberDiff line numberDiff line change
@@ -3,25 +3,25 @@
33
import java.util.Arrays;
44

55
public class _646 {
6+
/**
7+
* Although this problem could be solved using DP, greedy is more efficient in both time and space complexity.
8+
*/
69
public static class Solution1 {
710
/**
8-
* credit: https://discuss.leetcode.com/topic/96804/java-o-nlog-n-time-o-1-space
11+
* credit: https://leetcode.com/problems/maximum-length-of-pair-chain/editorial/
912
*/
1013
public int findLongestChain(int[][] pairs) {
11-
Arrays.sort(pairs, (o1, o2) -> o1[1] - o2[1]);
12-
int result = 0;
13-
int n = pairs.length;
14-
int i = -1;
15-
while (++i < n) {
16-
result++;
17-
int curEnd = pairs[i][1];
18-
while (i + 1 < n && pairs[i + 1][0] <= curEnd) {
19-
/**This means, we'll keep incrementing i until pairs[i+1][0] is
20-
* exactly greater than curEnd.*/
21-
i++;
14+
//sort by the second element
15+
Arrays.sort(pairs, (a, b) -> a[1] - b[1]);
16+
int ans = 0;
17+
int prev = Integer.MIN_VALUE;
18+
for (int[] pair : pairs) {
19+
if (pair[0] > prev) {
20+
ans++;
21+
prev = pair[1];
2222
}
2323
}
24-
return result;
24+
return ans;
2525
}
2626
}
2727

@@ -30,7 +30,7 @@ public static class Solution2 {
3030
* credit: https://leetcode.com/problems/maximum-length-of-pair-chain/discuss/105623/Java-Very-Simple-without-DP
3131
*/
3232
public int findLongestChain(int[][] pairs) {
33-
//sort by pair[0]
33+
//sort by the first element
3434
Arrays.sort(pairs, (a, b) -> a[0] - b[0]);
3535
int len = 0;
3636
int pre = Integer.MIN_VALUE;

0 commit comments

Comments
 (0)