Simple Java Solution, Greedy solution


  • 0
    D

    ...
    public class Solution {
    public boolean canPlaceFlowers(int[] bed, int n) {
    if (bed == null && bed.length == 0) {
    return n == 0;
    }

        int count = 0;
        for (int i = 0; i < bed.length; i++) {
            if (bed[i] == 0) {
                //if (previous is empty or current is the first bed) and (next is empty or current is the last bed)
                if ((i == 0 ||  bed[i - 1] == 0) && (i == bed.length - 1 || bed[i + 1] == 0)) {
                    //set bed to 1 as planted
                    bed[i] = 1;
                    count++;
                }
            }
        }
        return n <= count;
    }
    

    }
    ...


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.