Problem No: - 605("Can Place Flowers")

 

Approach

    check one by one

Complexity

    
  • Time complexity: - O(n)
  • Space complexity: - O(1)
Solution Link: - https://leetcode.com/problems/can-place-flowers/solutions/5650855/java-solution/

Code


class Solution {
    public boolean canPlaceFlowers(int[] flowerbed, int n) {
        int count = 0;
        boolean result;
        if(n == 0)
            result = true;
        else
            result = false;
        if(flowerbed.length == 1 && n == 1){
            if(flowerbed[0] == 0)
                return true;
            else
                return false;
        }
        if(flowerbed[0] == 0 && count < n){
            if(flowerbed[1] != 1){
                flowerbed[0] = 1;
                count++;
                result = true;
            }else{
                result = false;
                flowerbed[0] = 0;
            }
        }
        if(flowerbed[flowerbed.length-1] == 0 && count < n){
            if(flowerbed[flowerbed.length-2] != 1){
                flowerbed[flowerbed.length-1] = 1;
                count++;
                result = true;
            }else{
                result = false;
                flowerbed[flowerbed.length-1] = 0;
            }
        }
        int i = 1;
        while(count < n && i < flowerbed.length-1){
            if(flowerbed[i] != 1){
                int temp = flowerbed[i];
                flowerbed[i] = 1;
                if(flowerbed[i-1] != 1 && flowerbed[i+1] != 1){
                    count++;
                    result = true;
                }else{
                    result = false;
                    flowerbed[i] = temp;
                }
            }
            i++;
        }
        return result;
    }   
}

Comments

Popular posts from this blog

3Sum Closest: O(n²) Two-Pointer Magic 🚀 leetcode: 16

Kadane's Algorithm: Maximum Subarray Problem - LeetCode(53) Solution

LeetCode Problem: Implement pow(x, n) leetcode:- 50