-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathCanPlaceFlowers.java
34 lines (26 loc) · 1.05 KB
/
CanPlaceFlowers.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
package array_string;
public class CanPlaceFlowers {
public boolean canPlaceFlowers(int[] garden, int numFlowers) {
if (numFlowers == 0) return true;
int availableSpots = 0;
int index = 0;
while (index < garden.length) {
if (garden[index] == 0
&& (index == 0 || garden[index - 1] == 0)
&& (index == garden.length - 1 || garden[index + 1] == 0)) {
garden[index] = 1; // plant a flower
availableSpots++;
index += 2; // skip next plot
} else {
index++;
}
}
return availableSpots >= numFlowers;
}
public static void main(String[] args) {
CanPlaceFlowers arrangement = new CanPlaceFlowers();
assert arrangement.canPlaceFlowers(new int[]{1, 0, 0, 0, 1}, 1) == true : "Test case 1 failed";
assert arrangement.canPlaceFlowers(new int[]{1, 0, 0, 0, 1}, 2) == false : "Test case 2 failed";
System.out.println("All tests passed!");
}
}