We want the longest path of points where both x and y strictly increase, and the path must include coordinates[k]. This is a 2D variant of the Longest Increasing Subsequence (LIS) problem. We can sort the points, use DP to track the longest path ending at each point, and ensure the path includes the required point.
classSolution {
public:int longestIncreasingPath(vector<vector<int>>& coordinates, int k) {
int n = coordinates.size();
vector<pair<int,int>> pts;
for (auto& p : coordinates) pts.emplace_back(p[0], p[1]);
sort(pts.begin(), pts.end());
vector<int> dp(n, 1);
int ans =1;
for (int i =0; i < n; ++i) {
for (int j =0; j < i; ++j) {
if (pts[j].first < pts[i].first && pts[j].second < pts[i].second)
dp[i] = max(dp[i], dp[j]+1);
}
}
// Find all indices matching coordinates[k]
for (int i =0; i < n; ++i) {
if (pts[i].first == coordinates[k][0] && pts[i].second == coordinates[k][1])
ans = max(ans, dp[i]);
}
return ans;
}
};
classSolution {
publicintlongestIncreasingPath(int[][] coordinates, int k) {
int n = coordinates.length;
int[][] pts =newint[n][2];
for (int i = 0; i < n; i++) pts[i]= coordinates[i];
Arrays.sort(pts, (a, b) -> a[0]== b[0]? a[1]-b[1] : a[0]-b[0]);
int[] dp =newint[n];
Arrays.fill(dp, 1);
int ans = 1;
for (int i = 0; i < n; i++) {
for (int j = 0; j < i; j++) {
if (pts[j][0]< pts[i][0]&& pts[j][1]< pts[i][1])
dp[i]= Math.max(dp[i], dp[j]+1);
}
}
for (int i = 0; i < n; i++) {
if (pts[i][0]== coordinates[k][0]&& pts[i][1]== coordinates[k][1])
ans = Math.max(ans, dp[i]);
}
return ans;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
classSolution {
funlongestIncreasingPath(coordinates: Array<IntArray>, k: Int): Int {
val n = coordinates.size
val pts = coordinates.map { it.copyOf() }.sortedWith(compareBy({it[0]}, {it[1]}))
val dp = IntArray(n) { 1 }
var ans = 1for (i in0 until n) {
for (j in0 until i) {
if (pts[j][0] < pts[i][0] && pts[j][1] < pts[i][1])
dp[i] = maxOf(dp[i], dp[j]+1)
}
}
for (i in0 until n) {
if (pts[i][0] == coordinates[k][0] && pts[i][1] == coordinates[k][1])
ans = maxOf(ans, dp[i])
}
return ans
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
classSolution:
deflongestIncreasingPath(self, coordinates: list[list[int]], k: int) -> int:
n = len(coordinates)
pts = sorted(coordinates)
dp = [1]*n
for i in range(n):
for j in range(i):
if pts[j][0] < pts[i][0] and pts[j][1] < pts[i][1]:
dp[i] = max(dp[i], dp[j]+1)
ans =1for i in range(n):
if pts[i][0] == coordinates[k][0] and pts[i][1] == coordinates[k][1]:
ans = max(ans, dp[i])
return ans