LeetCode 75

Can Place Flowers

Problem
LC 605
Topic
Array / String
File
official75_LC605CanPlaceFlowers.java
Path
pkg5leetcode/official75/official75_LC605CanPlaceFlowers.java
Package
pkg5leetcode.official75
Command
java pkg5leetcode/official75/official75_LC605CanPlaceFlowers.java
Approach
Greedy plant when plot and neighbors empty.
Complexity
Time O(n), Space O(1)

LeetCode solutions

There is no in-browser runner. This is the file from the curriculum, unchanged.

pkg5leetcode/official75/official75_LC605CanPlaceFlowers.java
1package pkg5leetcode.official75;2 3/*4 * Can Place Flowers | LC 6055 * APPROACH: Greedy plant when plot and neighbors empty.6 * COMPLEXITY: Time O(n), Space O(1)7 */8public class official75_LC605CanPlaceFlowers {9    static boolean canPlaceFlowers(int[] flowerbed, int n) {10        int count = 0;11        for (int i = 0; i < flowerbed.length; i++) {12            if (flowerbed[i] == 013                    && (i == 0 || flowerbed[i - 1] == 0)14                    && (i == flowerbed.length - 1 || flowerbed[i + 1] == 0)) {15                flowerbed[i] = 1;16                count++;17            }18        }19        return count >= n;20    }21 22    public static void main(String[] args) {23        check(canPlaceFlowers(new int[]{1,0,0,0,1}, 1), "case1");24        check(!canPlaceFlowers(new int[]{1,0,0,0,1}, 2), "case2");25        System.out.println("all tests passed");26    }27 28    static void check(boolean cond, String name) {29        if (!cond) throw new AssertionError("FAILED: " + name);30        System.out.println("  PASS " + name);31    }32}