-
Notifications
You must be signed in to change notification settings - Fork 889
/
CanPlaceFlowers.swift
42 lines (37 loc) · 1.26 KB
/
CanPlaceFlowers.swift
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
/**
* Question Link: https://leetcode.com/problems/can-place-flowers/
* Primary idea: Greedy algorithm. Place flowers as early as possible.
* Time Complexity: O(n), Space Complexity: O(1)
*
*/
class CanPlaceFlowers {
func canPlaceFlowers(_ flowerbed: [Int], _ n: Int) -> Bool {
var maxFlowersCouldPlant = 0, flowerbed = flowerbed
for i in 0..<flowerbed.count {
guard flowerbed[i] == 0 else {
continue
}
if i < 1 {
if flowerbed.count == 1 || flowerbed[i + 1] != 1 {
flowerbed[i] = 1
maxFlowersCouldPlant += 1
}
} else if i + 1 == flowerbed.count {
if flowerbed.count == 1 || flowerbed[i - 1] != 1 {
flowerbed[i] = 1
maxFlowersCouldPlant += 1
}
} else {
if flowerbed[i - 1] != 1 && flowerbed[i + 1] != 1 {
flowerbed[i] = 1
maxFlowersCouldPlant += 1
}
}
// early exit
if maxFlowersCouldPlant >= n {
return true
}
}
return maxFlowersCouldPlant >= n
}
}