1326. Minimum Number of Taps to Open to Water a Garden
1326. 灌溉花园的最少水龙头数目
Intuition
We can build a interval for each tap representing the area it covers. Each time we pick an interval, we choose the one who has the maximum ending value.
class Solution {
class Interval {
int start;
int end;
Interval(int start, int end) { this.start = start; this.end = end; }
public String toString() {
return '"' + " ".repeat(start) + "-".repeat(end - start) + '"';
}
}
public int minTaps(int n, int[] ranges) {
// O(nlogn): sort by start increasingly (or by end decreasingly in case of ties)
TreeSet<Interval> set = new TreeSet<>(
(ia, ib) -> ia.start < ib.start ? -1 : ib.start < ia.start ? 1 : ib.end - ia.end);
for (int i = 0; i < ranges.length; i++) {
set.add(new Interval(Math.max(i - ranges[i], 0), Math.min(i + ranges[i], n)));
}
Interval cur = set.iterator().next();
if (cur.start > 0) return -1;
int cnt = 1;
// O(n) - greedy
while (cur != null && cur.end < n) {
// find the next who starts from cur and has maximum end value
Interval next = null;
Iterator<Interval> iter = set.iterator();
while (iter.hasNext()) {
Interval tmp = iter.next();
if (tmp.start > cur.end) break;
if (tmp.start > cur.start && (next == null || tmp.end > next.end))
next = tmp;
}
cur = next;
cnt++;
}
return cur == null ? -1 : cnt;
}
}
On the case 15/35 which I first get WA, we can print the sorted intervals as follows (input n: 35
, ranges: [1,0,4,0,4,1,4,3,1,1,1,2,1,4,0,3,0,3,0,3,0,5,3,0,0,1,2,1,2,4,3,0,1,0,5,2]
):
[
"--------", [0,8]
"------",
"-",
" ",
" --------",
" ",
" ------",
" --",
" --",
" --",
" --------", [9,17]
" ----",
" --",
" --",
" ------",
" ------",
" ",
" ----------",
" ------",
" ",
" ",
" ------",
" ",
" ",
" ----",
" --",
" ",
" --------",
" ----",
" --",
" ------",
" ------",
" --",
" ",
" --",
" "
]
where “-” means an area is covered by a certain tap and " " means not. You can see taps with range[i] == 0
(such as i = 2, 3, ...
in this case) covers nothing. First time, we pick [0, 8]
; and for the next, [9, 17]
is not valid due to area [8, 9]
is missed.