Can Place Flowers
Description
Input: flowerbed = [1,0,0,0,1], n = 1
Output: TrueInput: flowerbed = [1,0,0,0,1], n = 2
Output: FalseSolutions
My solution
Optimal solution
Last updated
Input: flowerbed = [1,0,0,0,1], n = 1
Output: TrueInput: flowerbed = [1,0,0,0,1], n = 2
Output: FalseLast updated
class Solution {
public:
bool canPlaceFlowers(vector<int>& flowerbed, int n) {
int size = flowerbed.size();
int i = 0;
while(i < size && flowerbed[i] == 0) ++i;
n -= i == size ? (i + 1) / 2 : i / 2;
while(i < size){
int j = i + 1;
while(j < size && flowerbed[j] == 0) ++j;
n -= j == size ? (j - i - 1) / 2 : (j - i - 2) / 2;
if(n <= 0) return true;
i = j;
}
return n <= 0;
}
};class Solution {
public:
bool canPlaceFlowers(vector<int>& flowerbed, int n) {
int zeros = 1; // the essential part: setting # of zeros to 1
for(int num : flowerbed){
if(num == 0){
++zeros;
}else{
n -= (zeros - 1) / 2;
if(n <= 0) return true;
zeros = 0;
}
}
n -= zeros / 2;
return n <= 0;
}
};