|
| 1 | +// 1326. Minimum Number of Taps to Open to Water a Garden |
| 2 | +// 🔴 Hard |
| 3 | +// |
| 4 | +// https://leetcode.com/problems/minimum-number-of-taps-to-open-to-water-a-garden/ |
| 5 | +// |
| 6 | +// Tags: Array - Dynamic Programming - Greedy |
| 7 | + |
| 8 | +struct Solution; |
| 9 | +impl Solution { |
| 10 | + /// Using an auxiliary vector that stores the max reach of each tap, we can |
| 11 | + /// convert this problem to jump game 2, then visit each position and check |
| 12 | + /// if we can reach it and if we need to add a "jump" to reach it. |
| 13 | + /// |
| 14 | + /// Time complexity: O(n) - We iterate twice over all elements of the input |
| 15 | + /// and, both times, we do constant time work for each. |
| 16 | + /// Space complexity: O(n) - The auxiliary max_reach vector has size n. |
| 17 | + /// |
| 18 | + /// Runtime 0 ms Beats 100% |
| 19 | + /// Memory 2.44 MB Beats 20% |
| 20 | + pub fn min_taps(n: i32, ranges: Vec<i32>) -> i32 { |
| 21 | + let n = n as usize; |
| 22 | + let mut max_reach = vec![0; n + 1]; |
| 23 | + let (mut start, mut end); |
| 24 | + for i in 0..n + 1 { |
| 25 | + start = 0.max(i as i32 - ranges[i]) as usize; |
| 26 | + end = n.min(i + ranges[i] as usize); |
| 27 | + max_reach[start] = max_reach[start].max(end); |
| 28 | + } |
| 29 | + let mut taps = 0; |
| 30 | + let (mut curr_end, mut next_end) = (0, 0); |
| 31 | + for i in 0..n + 1 { |
| 32 | + if i > next_end { |
| 33 | + return -1; |
| 34 | + } |
| 35 | + if i > curr_end { |
| 36 | + taps += 1; |
| 37 | + curr_end = next_end; |
| 38 | + } |
| 39 | + next_end = next_end.max(max_reach[i]); |
| 40 | + } |
| 41 | + taps |
| 42 | + } |
| 43 | +} |
| 44 | + |
| 45 | +// Tests. |
| 46 | +fn main() { |
| 47 | + let tests = [ |
| 48 | + (3, vec![0, 0, 0, 0], -1), |
| 49 | + (5, vec![3, 4, 1, 1, 0, 0], 1), |
| 50 | + (7, vec![1, 2, 1, 0, 2, 1, 0, 1], 3), |
| 51 | + ]; |
| 52 | + for t in tests { |
| 53 | + assert_eq!(Solution::min_taps(t.0, t.1), t.2); |
| 54 | + } |
| 55 | + println!("\x1b[92m» All tests passed!\x1b[0m") |
| 56 | +} |
0 commit comments