|
8 | 8 | */
|
9 | 9 | public class LongestIncreasingSubsequenceNLogN {
|
10 | 10 |
|
11 |
| - /** |
12 |
| - * Finds the index of the smallest element in the array that is greater than |
13 |
| - * or equal to the target using binary search. If no such element exists, |
14 |
| - * returns the index where the target can be inserted to maintain sorted order. |
15 |
| - * |
16 |
| - * @param arr The array to search in (assumed to be sorted up to a certain point). |
17 |
| - * @param target The target value to find the lower bound for. |
18 |
| - * @return The index of the lower bound. |
19 |
| - */ |
20 |
| - private static int lowerBound(int[] arr, int target) { |
21 |
| - int l = 0, r = arr.length; |
| 11 | + /** |
| 12 | + * Finds the index of the smallest element in the array that is greater than |
| 13 | + * or equal to the target using binary search. The search is restricted to |
| 14 | + * the first `size` elements of the array. |
| 15 | + * |
| 16 | + * @param arr The array to search in (assumed to be sorted up to `size`). |
| 17 | + * @param size The number of valid elements in the array. |
| 18 | + * @param target The target value to find the lower bound for. |
| 19 | + * @return The index of the lower bound. |
| 20 | + */ |
| 21 | + private static int lowerBound(int[] arr, int target, int size) { |
| 22 | + int l = 0, r = size; |
22 | 23 |
|
23 | 24 | while (l < r) {
|
24 | 25 | int mid = l + (r - l) / 2;
|
@@ -54,7 +55,7 @@ public static int lengthOfLIS(int[] arr) {
|
54 | 55 |
|
55 | 56 | for (int x : arr) {
|
56 | 57 | // Find the position to replace or extend the subsequence
|
57 |
| - int index = lowerBound(tails, x); |
| 58 | + int index = lowerBound(tails, x, size); |
58 | 59 |
|
59 | 60 | // Update the tails array with the current element
|
60 | 61 | tails[index] = x;
|
|
0 commit comments