Facing the sun
JavaView on GFG
Time: O(n)
Space: O(1)
Problem Overview
Count buildings that can see the sunrise (no taller building to the left).
Advertisement
Intuition
Count buildings that can see the sunrise (no taller building to the left). Scan left to right tracking max height.
Algorithm
- 1maxH = 0. For each building: if height > maxH: count++, maxH = height.
Common Pitfalls
- • First building always sees sun. Each subsequent: sees sun only if taller than all previous. O(n).
Facing the sun.java
Java
// Approach: Greedy. A building faces sun if it is taller than all buildings to its left.
// Track the current maximum height from the left.
// Time: O(n) Space: O(1)
class Solution {
// Returns count buildings that can see sunlight
public int countBuildings(int[] height) {
int maxi = height[0];
int cnt = 1;
for (int i = 1; i < height.length; i++) {
if (height[i] > maxi) {
maxi = height[i];
cnt++;
}
}
return cnt;
}
}Advertisement
Was this solution helpful?