1+ package com .leetcode .arrays ;
2+
3+ import static org .junit .Assert .assertFalse ;
4+ import static org .junit .Assert .assertTrue ;
5+
6+ /**
7+ * Level: Easy
8+ * Problem Link: https://leetcode.com/problems/can-place-flowers/
9+ * Problem Description:
10+ * Suppose you have a long flowerBed in which some of the plots are planted and some are not. However, flowers cannot
11+ * be planted in adjacent plots - they would compete for water and both would die.
12+ * <p>
13+ * Given a flowerBed (represented as an array containing 0 and 1, where 0 means empty and 1 means not empty), and a
14+ * number n, return if n new flowers can be planted in it without violating the no-adjacent-flowers rule.
15+ * <p>
16+ * Example 1:
17+ * Input: flowerBed = [1,0,0,0,1], n = 1
18+ * Output: True
19+ * <p>
20+ * Example 2:
21+ * Input: flowerBed = [1,0,0,0,1], n = 2
22+ * Output: False
23+ * <p>
24+ * Note:
25+ * The input array won't violate no-adjacent-flowers rule.
26+ * The input array size is in the range of [1, 20000].
27+ * n is a non-negative integer which won't exceed the input array size.
28+ *
29+ * @author rampatra
30+ * @since 2019-07-24
31+ */
32+ public class CanPlaceFlowers {
33+
34+ /**
35+ * Time Complexity: O(n)
36+ * Space Complexity: O(1)
37+ * Runtime: <a href="https://leetcode.com/submissions/detail/246312039/">1 ms</a>.
38+ *
39+ * @param flowerBed
40+ * @param n
41+ * @return
42+ */
43+ public static boolean canPlaceFlowers (int [] flowerBed , int n ) {
44+ int i = 0 , count = 0 ;
45+ while (i < flowerBed .length ) {
46+ if (flowerBed [i ] == 0 && (i == 0 || flowerBed [i - 1 ] == 0 ) && (i == flowerBed .length - 1 || flowerBed [i + 1 ] == 0 )) {
47+ flowerBed [i ++] = 1 ;
48+ count ++;
49+ }
50+ if (count >= n )
51+ return true ;
52+ i ++;
53+ }
54+ return false ;
55+ }
56+
57+ public static void main (String [] args ) {
58+ assertTrue (canPlaceFlowers (new int []{0 }, 0 ));
59+ assertTrue (canPlaceFlowers (new int []{0 }, 1 ));
60+ assertTrue (canPlaceFlowers (new int []{1 }, 0 ));
61+ assertFalse (canPlaceFlowers (new int []{1 }, 1 ));
62+ assertTrue (canPlaceFlowers (new int []{1 , 0 , 0 , 0 , 1 }, 1 ));
63+ assertFalse (canPlaceFlowers (new int []{1 , 0 , 0 , 0 , 1 }, 2 ));
64+ assertFalse (canPlaceFlowers (new int []{1 , 0 , 0 , 0 , 0 , 1 }, 2 ));
65+ assertTrue (canPlaceFlowers (new int []{1 , 0 , 0 , 0 , 1 , 0 , 0 }, 2 ));
66+ }
67+ }
0 commit comments