[LeetCode] Can Place Flowers

605. Can Place Flowers

You have a long flowerbed in which some of the plots are planted, and some are not. However, flowers cannot be planted in adjacent plots.

Given an integer array flowerbed containing 0‘s and 1‘s, where 0 means empty and 1 means not empty, and an integer n, return if n new flowers can be planted in the flowerbed without violating the no-adjacent-flowers rule.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Solution {
public:
bool canPlaceFlowers(vector<int>& A, int n) {
for(int i = 0; i < A.size(); i++) {
bool ok = true;
if(A[i]) ok = false;
if(i - 1 >= 0 and A[i-1]) ok = false;
if(i + 1 < A.size() and A[i+1]) ok = false;
if(ok) {
A[i] = 1;
n -= 1;
}
}
return n <= 0;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2023/03/20/PS/LeetCode/can-place-flowers/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.