Problem Summary

You are given an array arr[] where each element represents the height of a building.

Sunlight comes from the left side.

A building can see sunlight if:

Important:

Key Insight

A building gets sunlight if its height is:

greater than or equal to the maximum height seen so far from the left

Concept (Greedy Approach)

We traverse the array from left to right and track:

Rule:

If:

current height >= maxHeight

It gets sunlight.

Then:

Example Walkthrough

Input

arr = [6, 2, 8, 4, 11, 13]

Step-by-step

IndexHeightmaxHeightGets Sunlight?Count
066Yes1
126No1
288Yes2
348No2
41111Yes3
51313Yes4

Output

4

Another Example

Input

arr = [3, 3, 3, 1]
HeightConditionResult
3First buildingYES
3Equal heightYES
3Equal heightYES
1SmallerNO

Output

3

Algorithm (Simple Steps)

Java Code

class Solution {
    public int visibleBuildings(int arr[]) {
        int maxHeight = 0;
        int count = 0;

        for (int height : arr) {
            if (height >= maxHeight) {
                count++;
                maxHeight = height;
            }
        }

        return count;
    }
}

Complexity

Key Takeaways