Untitled
unknown
plain_text
13 days ago
1.3 kB
3
Indexable
import java.util.Arrays; public class RussianDollEnvelopesLIS { public int maxEnvelopes(int[][] envelopes) { int n = envelopes.length; // Step 1: Sort envelopes by width (ascending), and by height (ascending) when widths are equal Arrays.sort(envelopes, (a, b) -> a[0] == b[0] ? a[1] - b[1] : a[0] - b[0]); // Step 2: dp[i] represents the LIS ending at envelope i int[] dp = new int[n]; Arrays.fill(dp, 1); int maxLength = 1; // Step 3: Calculate LIS ending at each envelope for (int i = 1; i < n; i++) { for (int j = 0; j < i; j++) { if (envelopes[i][0] > envelopes[j][0] && envelopes[i][1] > envelopes[j][1]) { dp[i] = Math.max(dp[i], dp[j] + 1); } } maxLength = Math.max(maxLength, dp[i]); } return maxLength; } public static void main(String[] args) { RussianDollEnvelopesLIS rde = new RussianDollEnvelopesLIS(); System.out.println(rde.maxEnvelopes(new int[][]{{5, 4}, {6, 4}, {6, 7}, {2, 3}})); // Output: 3 System.out.println(rde.maxEnvelopes(new int[][]{{1, 1}, {1, 1}, {1, 1}})); // Output: 1 } }
Editor is loading...
Leave a Comment