|
| 1 | +/** |
| 2 | + * 2158. Amount of New Area Painted Each Day |
| 3 | + * https://leetcode.com/problems/amount-of-new-area-painted-each-day/ |
| 4 | + * Difficulty: Hard |
| 5 | + * |
| 6 | + * There is a long and thin painting that can be represented by a number line. You are given |
| 7 | + * a 0-indexed 2D integer array paint of length n, where paint[i] = [starti, endi]. This means |
| 8 | + * that on the ith day you need to paint the area between starti and endi. |
| 9 | + * |
| 10 | + * Painting the same area multiple times will create an uneven painting so you only want to |
| 11 | + * paint each area of the painting at most once. |
| 12 | + * |
| 13 | + * Return an integer array worklog of length n, where worklog[i] is the amount of new area that |
| 14 | + * you painted on the ith day. |
| 15 | + */ |
| 16 | + |
| 17 | +/** |
| 18 | + * @param {number[][]} paint |
| 19 | + * @return {number[]} |
| 20 | + */ |
| 21 | +var amountPainted = function(paint) { |
| 22 | + const intervals = new Map(); |
| 23 | + const result = []; |
| 24 | + |
| 25 | + for (const [start, end] of paint) { |
| 26 | + let left = start; |
| 27 | + let right = end; |
| 28 | + let paintAmount = right - left; |
| 29 | + |
| 30 | + const keys = Array.from(intervals.keys()).sort((a, b) => a - b); |
| 31 | + const toRemove = []; |
| 32 | + let merged = false; |
| 33 | + |
| 34 | + for (const key of keys) { |
| 35 | + const value = intervals.get(key); |
| 36 | + |
| 37 | + if (key > right || value < left) continue; |
| 38 | + |
| 39 | + if (!merged && key <= left && value >= left) { |
| 40 | + left = Math.min(left, key); |
| 41 | + right = Math.max(right, value); |
| 42 | + paintAmount = Math.max(0, end - Math.max(start, value)); |
| 43 | + toRemove.push(key); |
| 44 | + merged = true; |
| 45 | + } else if (key >= left && key < right) { |
| 46 | + paintAmount -= Math.min(right, value) - key; |
| 47 | + right = Math.max(right, value); |
| 48 | + toRemove.push(key); |
| 49 | + } else if (value > left && value <= right) { |
| 50 | + paintAmount -= value - Math.max(left, key); |
| 51 | + left = Math.min(left, key); |
| 52 | + toRemove.push(key); |
| 53 | + } |
| 54 | + } |
| 55 | + |
| 56 | + for (const key of toRemove) { |
| 57 | + intervals.delete(key); |
| 58 | + } |
| 59 | + |
| 60 | + intervals.set(left, right); |
| 61 | + result.push(Math.max(0, paintAmount)); |
| 62 | + } |
| 63 | + |
| 64 | + return result; |
| 65 | +}; |
0 commit comments