From 5a9d67f37d3560cf8c5a0656c1713adbb02903d1 Mon Sep 17 00:00:00 2001 From: Matej Focko Date: Tue, 18 Jan 2022 13:38:21 +0100 Subject: [PATCH] problems: add can place flowers Signed-off-by: Matej Focko --- problems/can-place-flowers.cpp | 44 ++++++++++++++++++++++++++++++++++ 1 file changed, 44 insertions(+) create mode 100644 problems/can-place-flowers.cpp diff --git a/problems/can-place-flowers.cpp b/problems/can-place-flowers.cpp new file mode 100644 index 0000000..4a63f31 --- /dev/null +++ b/problems/can-place-flowers.cpp @@ -0,0 +1,44 @@ +#include +#include + +using std::vector; + +class Solution { + public: + bool canPlaceFlowers(vector &flowerbed, int n) { + int count = 0; + + int left = 0, right; + for (vector::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; +}