|
| 1 | +/** |
| 2 | + * 2407. Longest Increasing Subsequence II |
| 3 | + * https://leetcode.com/problems/longest-increasing-subsequence-ii/ |
| 4 | + * Difficulty: Hard |
| 5 | + * |
| 6 | + * You are given an integer array nums and an integer k. |
| 7 | + * |
| 8 | + * Find the longest subsequence of nums that meets the following requirements: |
| 9 | + * - The subsequence is strictly increasing and |
| 10 | + * - The difference between adjacent elements in the subsequence is at most k. |
| 11 | + * |
| 12 | + * Return the length of the longest subsequence that meets the requirements. |
| 13 | + * |
| 14 | + * A subsequence is an array that can be derived from another array by deleting some or |
| 15 | + * no elements without changing the order of the remaining elements. |
| 16 | + */ |
| 17 | + |
| 18 | +/** |
| 19 | + * @param {number[]} nums |
| 20 | + * @param {number} k |
| 21 | + * @return {number} |
| 22 | + */ |
| 23 | +var lengthOfLIS = function(nums, k) { |
| 24 | + const maxValue = Math.max(...nums); |
| 25 | + const tree = new Array(4 * maxValue).fill(0); |
| 26 | + |
| 27 | + for (const currentNum of nums) { |
| 28 | + const rangeStart = Math.max(1, currentNum - k); |
| 29 | + const rangeEnd = currentNum - 1; |
| 30 | + |
| 31 | + const bestPreviousLength = rangeEnd >= rangeStart |
| 32 | + ? queryRange(1, 1, maxValue, rangeStart, rangeEnd) : 0; |
| 33 | + updatePosition(1, 1, maxValue, currentNum, bestPreviousLength + 1); |
| 34 | + } |
| 35 | + |
| 36 | + return queryRange(1, 1, maxValue, 1, maxValue); |
| 37 | + |
| 38 | + function updatePosition(nodeIndex, treeStart, treeEnd, position, newLength) { |
| 39 | + if (treeStart === treeEnd) { |
| 40 | + tree[nodeIndex] = Math.max(tree[nodeIndex], newLength); |
| 41 | + } else { |
| 42 | + const treeMid = Math.floor((treeStart + treeEnd) / 2); |
| 43 | + if (position <= treeMid) { |
| 44 | + updatePosition(2 * nodeIndex, treeStart, treeMid, position, newLength); |
| 45 | + } else { |
| 46 | + updatePosition(2 * nodeIndex + 1, treeMid + 1, treeEnd, position, newLength); |
| 47 | + } |
| 48 | + tree[nodeIndex] = Math.max(tree[2 * nodeIndex], tree[2 * nodeIndex + 1]); |
| 49 | + } |
| 50 | + } |
| 51 | + |
| 52 | + function queryRange(nodeIndex, treeStart, treeEnd, queryStart, queryEnd) { |
| 53 | + if (queryEnd < treeStart || treeEnd < queryStart) { |
| 54 | + return 0; |
| 55 | + } |
| 56 | + if (queryStart <= treeStart && treeEnd <= queryEnd) { |
| 57 | + return tree[nodeIndex]; |
| 58 | + } |
| 59 | + const mid = Math.floor((treeStart + treeEnd) / 2); |
| 60 | + return Math.max( |
| 61 | + queryRange(2 * nodeIndex, treeStart, mid, queryStart, queryEnd), |
| 62 | + queryRange(2 * nodeIndex + 1, mid + 1, treeEnd, queryStart, queryEnd) |
| 63 | + ); |
| 64 | + } |
| 65 | +}; |
0 commit comments