|
| 1 | +/** |
| 2 | + * 3356. Zero Array Transformation II |
| 3 | + * https://leetcode.com/problems/zero-array-transformation-ii/ |
| 4 | + * Difficulty: Medium |
| 5 | + * |
| 6 | + * You are given an integer array nums of length n and a 2D array queries where |
| 7 | + * queries[i] = [li, ri, vali]. |
| 8 | + * |
| 9 | + * Each queries[i] represents the following action on nums: |
| 10 | + * - Decrement the value at each index in the range [li, ri] in nums by at most vali. |
| 11 | + * - The amount by which each value is decremented can be chosen independently for each index. |
| 12 | + * |
| 13 | + * A Zero Array is an array with all its elements equal to 0. |
| 14 | + * |
| 15 | + * Return the minimum possible non-negative value of k, such that after processing the first |
| 16 | + * k queries in sequence, nums becomes a Zero Array. If no such k exists, return -1. |
| 17 | + */ |
| 18 | + |
| 19 | +/** |
| 20 | + * @param {number[]} nums |
| 21 | + * @param {number[][]} queries |
| 22 | + * @return {number} |
| 23 | + */ |
| 24 | +var minZeroArray = function(nums, queries) { |
| 25 | + const diff = new Array(nums.length + 1).fill(0); |
| 26 | + const total = nums.reduce((sum, num) => sum + num, 0); |
| 27 | + let left = 0; |
| 28 | + let right = queries.length - 1; |
| 29 | + let result = -1; |
| 30 | + |
| 31 | + if (total === 0) { |
| 32 | + return 0; |
| 33 | + } |
| 34 | + |
| 35 | + while (left <= right) { |
| 36 | + const mid = Math.floor((left + right) / 2); |
| 37 | + if (canZeroOut(mid)) { |
| 38 | + result = mid + 1; |
| 39 | + right = mid - 1; |
| 40 | + } else { |
| 41 | + left = mid + 1; |
| 42 | + } |
| 43 | + } |
| 44 | + |
| 45 | + return result; |
| 46 | + |
| 47 | + function canZeroOut(k) { |
| 48 | + const tempDiff = new Array(nums.length + 1).fill(0); |
| 49 | + for (let i = 0; i <= k; i++) { |
| 50 | + const [left, right, val] = queries[i]; |
| 51 | + tempDiff[left] += val; |
| 52 | + if (right + 1 < nums.length) tempDiff[right + 1] -= val; |
| 53 | + } |
| 54 | + |
| 55 | + let current = 0; |
| 56 | + let reduction = 0; |
| 57 | + for (let i = 0; i < nums.length; i++) { |
| 58 | + current = Math.max(0, current + tempDiff[i]); |
| 59 | + reduction += Math.min(nums[i], current); |
| 60 | + if (reduction >= total) return true; |
| 61 | + } |
| 62 | + return reduction >= total; |
| 63 | + } |
| 64 | +}; |
0 commit comments