problems: add can place flowers
Signed-off-by: Matej Focko <mfocko@redhat.com>
This commit is contained in:
parent
2c664a305d
commit
5a9d67f37d
1 changed files with 44 additions and 0 deletions
44
problems/can-place-flowers.cpp
Normal file
44
problems/can-place-flowers.cpp
Normal file
|
@ -0,0 +1,44 @@
|
|||
#include <cassert>
|
||||
#include <vector>
|
||||
|
||||
using std::vector;
|
||||
|
||||
class Solution {
|
||||
public:
|
||||
bool canPlaceFlowers(vector<int> &flowerbed, int n) {
|
||||
int count = 0;
|
||||
|
||||
int left = 0, right;
|
||||
for (vector<int>::size_type i = 0; i < flowerbed.size(); i++) {
|
||||
right = (i + 1 < flowerbed.size()) ? flowerbed[i + 1] : 0;
|
||||
|
||||
if (left == 0 && flowerbed[i] == 0 && right == 0) {
|
||||
count++;
|
||||
left = 1;
|
||||
} else {
|
||||
left = flowerbed[i];
|
||||
}
|
||||
}
|
||||
|
||||
return count >= n;
|
||||
}
|
||||
};
|
||||
|
||||
int main() {
|
||||
Solution s;
|
||||
|
||||
std::vector flowers{1, 0, 0, 0, 1};
|
||||
assert(s.canPlaceFlowers(flowers, 1));
|
||||
assert(!s.canPlaceFlowers(flowers, 2));
|
||||
|
||||
flowers = {1, 0, 0, 0, 0, 1};
|
||||
assert(!s.canPlaceFlowers(flowers, 2));
|
||||
|
||||
flowers = {1, 0, 0, 0, 1, 0, 0};
|
||||
assert(s.canPlaceFlowers(flowers, 2));
|
||||
|
||||
flowers = {0, 0, 1, 0, 0};
|
||||
assert(s.canPlaceFlowers(flowers, 1));
|
||||
|
||||
return 0;
|
||||
}
|
Loading…
Reference in a new issue