-
Notifications
You must be signed in to change notification settings - Fork 0
/
Solution29.java
102 lines (85 loc) · 2.72 KB
/
Solution29.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
/*
A gallery with plants is divided into n parts, numbered 0, 1, 2, 3, ..., n-1. There are provisions for attaching water sprinklers in every division. A sprinkler with range x at division i can water all divisions from i-x to i+x.
Given an array gallery[] consisting of n integers, where gallery[i] is the range of the sprinkler at partition i (a power of -1 indicates no sprinkler attached), return the minimum number of sprinklers that need to be turned on to water the entire gallery. If there is no possible way to water the full length using the given sprinklers, print -1.
Example 1:
Input:
n = 6
gallery[] = {-1, 2, 2, -1, 0, 0}
Output:
2
Explanation:
Sprinklers at index 2 and 5
can water the full gallery, span of
sprinkler at index 2 = [0,4] and span
of sprinkler at index 5 = [5,5].
Example 2:
Input:
n = 9
gallery[ ] = {2, 3, 4, -1, 2, 0, 0, -1, 0}
Output:
-1
Explanation:
No sprinkler can throw water
at index 7. Hence all plants cannot be
watered.
Example 3:
Input:
n = 9
gallery[ ] = {2, 3, 4, -1, 0, 0, 0, 0, 0}
Output:
3
Explanation:
Sprinkler at indexes 2, 7 and
8 together can water all plants.
Your task:
You do not have to take any input or print anything. Your task is to complete the function min_sprinklers() which takes the array gallery[ ] and the integer n as input parameters and returns the minimum number of sprinklers that need to be turned on to water the entire gallery.
Expected Time Complexity: O( nlog(n) )
Expected Auxiliary Space: O( n )
Constraints:
1 ≤ n ≤ 105
gallery[i] ≤ 50
*/
class Pair{
int x;
int y;
public Pair(int x,int y)
{
this.x = x;
this.y = y;
}
}
class Solution
{
int min_sprinklers(int gallery[], int n)
{
List <Pair> sprinklers = new ArrayList<>();
for(int i=0; i<n; i++)
if(gallery[i] > -1)
sprinklers.add( new Pair( i-gallery[i], i+gallery[i] ) );
Collections.sort(sprinklers, new Comparator<Pair>(){
@Override
public int compare(Pair p1,Pair p2)
{
return p1.x - p2.x;
}
});
int target=0, sprinklers_on=0, i=0;
while(target<n)
{
if(i==sprinklers.size() || sprinklers.get(i).x>target)
return -1;
int max_range = sprinklers.get(i).y;
while( i+1<sprinklers.size() && sprinklers.get(i+1).x<=target )
{
i++;
max_range = Math.max( max_range, sprinklers.get(i).y );
}
if(max_range<target)
return -1;
sprinklers_on++;
target = max_range +1;
i++;
}
return sprinklers_on;
}
}