|
| 1 | +/** |
| 2 | + * 1488. Avoid Flood in The City |
| 3 | + * https://leetcode.com/problems/avoid-flood-in-the-city/ |
| 4 | + * Difficulty: Medium |
| 5 | + * |
| 6 | + * Your country has an infinite number of lakes. Initially, all the lakes are empty, but when it |
| 7 | + * rains over the nth lake, the nth lake becomes full of water. If it rains over a lake that is |
| 8 | + * full of water, there will be a flood. Your goal is to avoid floods in any lake. |
| 9 | + * |
| 10 | + * Given an integer array rains where: |
| 11 | + * - rains[i] > 0 means there will be rains over the rains[i] lake. |
| 12 | + * - rains[i] == 0 means there are no rains this day and you can choose one lake this day and |
| 13 | + * dry it. |
| 14 | + * |
| 15 | + * Return an array ans where: |
| 16 | + * - ans.length == rains.length |
| 17 | + * - ans[i] == -1 if rains[i] > 0. |
| 18 | + * - ans[i] is the lake you choose to dry in the ith day if rains[i] == 0. |
| 19 | + * |
| 20 | + * If there are multiple valid answers return any of them. If it is impossible to avoid flood return |
| 21 | + * an empty array. |
| 22 | + * |
| 23 | + * Notice that if you chose to dry a full lake, it becomes empty, but if you chose to dry an empty |
| 24 | + * lake, nothing changes. |
| 25 | + */ |
| 26 | + |
| 27 | +/** |
| 28 | + * @param {number[]} rains |
| 29 | + * @return {number[]} |
| 30 | + */ |
| 31 | +var avoidFlood = function(rains) { |
| 32 | + const fullLakes = new Map(); |
| 33 | + const dryDays = []; |
| 34 | + const result = new Array(rains.length).fill(-1); |
| 35 | + |
| 36 | + for (let i = 0; i < rains.length; i++) { |
| 37 | + if (rains[i] === 0) { |
| 38 | + dryDays.push(i); |
| 39 | + } else { |
| 40 | + if (fullLakes.has(rains[i])) { |
| 41 | + const lastRain = fullLakes.get(rains[i]); |
| 42 | + let found = false; |
| 43 | + for (let j = 0; j < dryDays.length; j++) { |
| 44 | + if (dryDays[j] > lastRain) { |
| 45 | + result[dryDays[j]] = rains[i]; |
| 46 | + dryDays.splice(j, 1); |
| 47 | + found = true; |
| 48 | + break; |
| 49 | + } |
| 50 | + } |
| 51 | + if (!found) return []; |
| 52 | + } |
| 53 | + fullLakes.set(rains[i], i); |
| 54 | + } |
| 55 | + } |
| 56 | + |
| 57 | + for (const dryDay of dryDays) { |
| 58 | + result[dryDay] = 1; |
| 59 | + } |
| 60 | + |
| 61 | + return result; |
| 62 | +}; |
0 commit comments