|
| 1 | +/** |
| 2 | + * 3495. Minimum Operations to Make Array Elements Zero |
| 3 | + * https://leetcode.com/problems/minimum-operations-to-make-array-elements-zero/ |
| 4 | + * Difficulty: Hard |
| 5 | + * |
| 6 | + * You are given a 2D array queries, where queries[i] is of the form [l, r]. Each |
| 7 | + * queries[i] defines an array of integers nums consisting of elements ranging |
| 8 | + * from l to r, both inclusive. |
| 9 | + * |
| 10 | + * In one operation, you can: |
| 11 | + * - Select two integers a and b from the array. |
| 12 | + * - Replace them with floor(a / 4) and floor(b / 4). |
| 13 | + * |
| 14 | + * Your task is to determine the minimum number of operations required to reduce all |
| 15 | + * elements of the array to zero for each query. Return the sum of the results for |
| 16 | + * all queries. |
| 17 | + */ |
| 18 | + |
| 19 | +/** |
| 20 | + * @param {number[][]} queries |
| 21 | + * @return {number} |
| 22 | + */ |
| 23 | +var minOperations = function(queries) { |
| 24 | + let result = 0; |
| 25 | + |
| 26 | + for (const [start, end] of queries) { |
| 27 | + let operationsNeeded = 0; |
| 28 | + |
| 29 | + for (let depth = 1, previousBound = 1; depth < 17; depth++) { |
| 30 | + const currentBound = previousBound * 4; |
| 31 | + const intersectionLeft = Math.max(start, previousBound); |
| 32 | + const intersectionRight = Math.min(end, currentBound - 1); |
| 33 | + |
| 34 | + if (intersectionRight >= intersectionLeft) { |
| 35 | + operationsNeeded += (intersectionRight - intersectionLeft + 1) * depth; |
| 36 | + } |
| 37 | + previousBound = currentBound; |
| 38 | + } |
| 39 | + |
| 40 | + result += Math.ceil(operationsNeeded / 2); |
| 41 | + } |
| 42 | + |
| 43 | + return result; |
| 44 | +}; |
0 commit comments