|
| 1 | +/** |
| 2 | + * 1649. Create Sorted Array through Instructions |
| 3 | + * https://leetcode.com/problems/create-sorted-array-through-instructions/ |
| 4 | + * Difficulty: Hard |
| 5 | + * |
| 6 | + * Given an integer array instructions, you are asked to create a sorted array from the elements in |
| 7 | + * instructions. You start with an empty container nums. For each element from left to right in |
| 8 | + * instructions, insert it into nums. The cost of each insertion is the minimum of the following: |
| 9 | + * - The number of elements currently in nums that are strictly less than instructions[i]. |
| 10 | + * - The number of elements currently in nums that are strictly greater than instructions[i]. |
| 11 | + * |
| 12 | + * For example, if inserting element 3 into nums = [1,2,3,5], the cost of insertion is min(2, 1) |
| 13 | + * (elements 1 and 2 are less than 3, element 5 is greater than 3) and nums will become [1,2,3,3,5]. |
| 14 | + * |
| 15 | + * Return the total cost to insert all elements from instructions into nums. Since the answer may |
| 16 | + * be large, return it modulo 109 + 7 |
| 17 | + */ |
| 18 | + |
| 19 | +/** |
| 20 | + * @param {number[]} instructions |
| 21 | + * @return {number} |
| 22 | + */ |
| 23 | +var createSortedArray = function(instructions) { |
| 24 | + const MOD = 1e9 + 7; |
| 25 | + const maxValue = Math.max(...instructions); |
| 26 | + const fenwickTree = new Array(maxValue + 1).fill(0); |
| 27 | + let totalCost = 0; |
| 28 | + |
| 29 | + for (let i = 0; i < instructions.length; i++) { |
| 30 | + const value = instructions[i]; |
| 31 | + const lessCount = query(value - 1); |
| 32 | + const greaterCount = i - query(value); |
| 33 | + totalCost = (totalCost + Math.min(lessCount, greaterCount)) % MOD; |
| 34 | + update(value); |
| 35 | + } |
| 36 | + |
| 37 | + return totalCost; |
| 38 | + |
| 39 | + function update(index) { |
| 40 | + for (let i = index; i <= maxValue; i += i & -i) { |
| 41 | + fenwickTree[i]++; |
| 42 | + } |
| 43 | + } |
| 44 | + |
| 45 | + function query(index) { |
| 46 | + let sum = 0; |
| 47 | + for (let i = index; i > 0; i -= i & -i) { |
| 48 | + sum += fenwickTree[i]; |
| 49 | + } |
| 50 | + return sum; |
| 51 | + } |
| 52 | +}; |
0 commit comments