|
| 1 | +/** |
| 2 | + * 1713. Minimum Operations to Make a Subsequence |
| 3 | + * https://leetcode.com/problems/minimum-operations-to-make-a-subsequence/ |
| 4 | + * Difficulty: Hard |
| 5 | + * |
| 6 | + * You are given an array target that consists of distinct integers and another integer array |
| 7 | + * arr that can have duplicates. |
| 8 | + * |
| 9 | + * In one operation, you can insert any integer at any position in arr. For example, if |
| 10 | + * arr = [1,4,1,2], you can add 3 in the middle and make it [1,4,3,1,2]. Note that you can |
| 11 | + * insert the integer at the very beginning or end of the array. |
| 12 | + * |
| 13 | + * Return the minimum number of operations needed to make target a subsequence of arr. |
| 14 | + * |
| 15 | + * A subsequence of an array is a new array generated from the original array by deleting some |
| 16 | + * elements (possibly none) without changing the remaining elements' relative order. For |
| 17 | + * example, [2,7,4] is a subsequence of [4,2,3,7,2,1,4] (the underlined elements), |
| 18 | + * while [2,4,2] is not. |
| 19 | + */ |
| 20 | + |
| 21 | +/** |
| 22 | + * @param {number[]} target |
| 23 | + * @param {number[]} arr |
| 24 | + * @return {number} |
| 25 | + */ |
| 26 | +var minOperations = function(target, arr) { |
| 27 | + const valueToIndex = new Map(target.map((val, i) => [val, i])); |
| 28 | + const sequence = arr.filter(val => valueToIndex.has(val)).map(val => valueToIndex.get(val)); |
| 29 | + |
| 30 | + const lis = []; |
| 31 | + for (const index of sequence) { |
| 32 | + const pos = binarySearch(lis, index); |
| 33 | + if (pos === lis.length) { |
| 34 | + lis.push(index); |
| 35 | + } else { |
| 36 | + lis[pos] = index; |
| 37 | + } |
| 38 | + } |
| 39 | + |
| 40 | + return target.length - lis.length; |
| 41 | +}; |
| 42 | + |
| 43 | +function binarySearch(arr, target) { |
| 44 | + let left = 0; |
| 45 | + let right = arr.length; |
| 46 | + |
| 47 | + while (left < right) { |
| 48 | + const mid = Math.floor((left + right) / 2); |
| 49 | + if (arr[mid] < target) { |
| 50 | + left = mid + 1; |
| 51 | + } else { |
| 52 | + right = mid; |
| 53 | + } |
| 54 | + } |
| 55 | + |
| 56 | + return left; |
| 57 | +} |
0 commit comments