Untitled
unknown
plain_text
10 months ago
1.5 kB
6
Indexable
class Solution {
public int minTaps(int n, int[] ranges) {
// First convert ranges to maximum reach array, just like jump lengths
int[] maxReach = new int[n + 1];
for (int i = 0; i <= n; i++) {
int start = Math.max(0, i - ranges[i]);
int end = Math.min(n, i + ranges[i]);
maxReach[start] = Math.max(maxReach[start], end);
}
// Now use identical structure to Jump Game II
int taps = 0; // counts minimum taps needed, like jumps
int i = 0; // start of current level
int j = 0; // end of current level (replacing currentEnd)
while (j < n) { // while we haven't covered the whole garden
int maxRange = 0; // tracks furthest reach from current level
// Explore all positions in current level
for (int index = i; index <= j; index++) {
maxRange = Math.max(maxRange, maxReach[index]);
}
// If we can't extend our reach, garden can't be watered
if (maxRange <= j) {
return -1;
}
// Move to next level
i = j + 1; // new level starts after current end
j = maxRange; // new level ends at our maximum reach
taps++;
}
return taps;
}
}Editor is loading...
Leave a Comment