|
| 1 | +/** |
| 2 | + * 2105. Watering Plants II |
| 3 | + * https://leetcode.com/problems/watering-plants-ii/ |
| 4 | + * Difficulty: Medium |
| 5 | + * |
| 6 | + * Alice and Bob want to water n plants in their garden. The plants are arranged in a row and are |
| 7 | + * labeled from 0 to n - 1 from left to right where the ith plant is located at x = i. |
| 8 | + * |
| 9 | + * Each plant needs a specific amount of water. Alice and Bob have a watering can each, initially |
| 10 | + * full. They water the plants in the following way: |
| 11 | + * - Alice waters the plants in order from left to right, starting from the 0th plant. Bob waters |
| 12 | + * the plants in order from right to left, starting from the (n - 1)th plant. They begin watering |
| 13 | + * the plants simultaneously. |
| 14 | + * - It takes the same amount of time to water each plant regardless of how much water it needs. |
| 15 | + * - Alice/Bob must water the plant if they have enough in their can to fully water it. Otherwise, |
| 16 | + * they first refill their can (instantaneously) then water the plant. |
| 17 | + * - In case both Alice and Bob reach the same plant, the one with more water currently in his/her |
| 18 | + * watering can should water this plant. If they have the same amount of water, then Alice should |
| 19 | + * water this plant. |
| 20 | + * |
| 21 | + * Given a 0-indexed integer array plants of n integers, where plants[i] is the amount of water the |
| 22 | + * ith plant needs, and two integers capacityA and capacityB representing the capacities of Alice's |
| 23 | + * and Bob's watering cans respectively, return the number of times they have to refill to water all |
| 24 | + * the plants. |
| 25 | + */ |
| 26 | + |
| 27 | +/** |
| 28 | + * @param {number[]} plants |
| 29 | + * @param {number} capacityA |
| 30 | + * @param {number} capacityB |
| 31 | + * @return {number} |
| 32 | + */ |
| 33 | +var minimumRefill = function(plants, capacityA, capacityB) { |
| 34 | + let result = 0; |
| 35 | + let left = 0; |
| 36 | + let right = plants.length - 1; |
| 37 | + let waterA = capacityA; |
| 38 | + let waterB = capacityB; |
| 39 | + |
| 40 | + while (left <= right) { |
| 41 | + if (left === right) { |
| 42 | + if (waterA >= waterB && waterA < plants[left]) result++; |
| 43 | + if (waterB > waterA && waterB < plants[right]) result++; |
| 44 | + break; |
| 45 | + } |
| 46 | + |
| 47 | + if (waterA < plants[left]) { |
| 48 | + waterA = capacityA; |
| 49 | + result++; |
| 50 | + } |
| 51 | + waterA -= plants[left++]; |
| 52 | + |
| 53 | + if (waterB < plants[right]) { |
| 54 | + waterB = capacityB; |
| 55 | + result++; |
| 56 | + } |
| 57 | + waterB -= plants[right--]; |
| 58 | + } |
| 59 | + |
| 60 | + return result; |
| 61 | +}; |
0 commit comments