|
| 1 | +/** |
| 2 | + * 699. Falling Squares |
| 3 | + * https://leetcode.com/problems/falling-squares/ |
| 4 | + * Difficulty: Hard |
| 5 | + * |
| 6 | + * There are several squares being dropped onto the X-axis of a 2D plane. |
| 7 | + * |
| 8 | + * You are given a 2D integer array positions where positions[i] = [lefti, sideLengthi] |
| 9 | + * represents the ith square with a side length of sideLengthi that is dropped with its |
| 10 | + * left edge aligned with X-coordinate lefti. |
| 11 | + * |
| 12 | + * Each square is dropped one at a time from a height above any landed squares. It then |
| 13 | + * falls downward (negative Y direction) until it either lands on the top side of another |
| 14 | + * square or on the X-axis. A square brushing the left/right side of another square does |
| 15 | + * not count as landing on it. Once it lands, it freezes in place and cannot be moved. |
| 16 | + * |
| 17 | + * After each square is dropped, you must record the height of the current tallest stack |
| 18 | + * of squares. |
| 19 | + * |
| 20 | + * Return an integer array ans where ans[i] represents the height described above after |
| 21 | + * dropping the ith square. |
| 22 | + */ |
| 23 | + |
| 24 | +/** |
| 25 | + * @param {number[][]} positions |
| 26 | + * @return {number[]} |
| 27 | + */ |
| 28 | +var fallingSquares = function(positions) { |
| 29 | + const map = new Map(); |
| 30 | + const result = []; |
| 31 | + let max = 0; |
| 32 | + |
| 33 | + for (const [left, side] of positions) { |
| 34 | + const right = left + side; |
| 35 | + let height = 0; |
| 36 | + |
| 37 | + for (const [start, [i, n]] of map) { |
| 38 | + const end = start + i; |
| 39 | + if (right > start && left < end) { |
| 40 | + height = Math.max(height, n); |
| 41 | + } |
| 42 | + } |
| 43 | + |
| 44 | + height += side; |
| 45 | + map.set(left, [side, height]); |
| 46 | + max = Math.max(max, height); |
| 47 | + result.push(max); |
| 48 | + } |
| 49 | + |
| 50 | + return result; |
| 51 | +}; |
0 commit comments