702686. Buildings receiving sunlight
Buildings receiving sunlight
Slug: buildings-receiving-sunlight3032
Difficulty: Easy
Id: 702686
Topic Tags: Arrays, Data Structures
Company Tags: Amazon, Microsoft
Summary
Given a list of buildings and their respective elevations, we need to determine which buildings receive direct sunlight. A building receives direct sunlight if the elevation of that building is higher than or equal to any building that comes after it in the list.
Detailed Explanation
To solve this problem, we can iterate through the list of buildings from left to right. For each building, we check if its elevation is greater than or equal to the elevation of any subsequent building. If it is, then we consider this building as receiving direct sunlight and mark it accordingly. We keep track of the last index where we found a building that receives direct sunlight. If no such building is found, then all buildings receive direct sunlight.
Here's a step-by-step breakdown:
- Initialize an empty array
sunlightReceiversto store the indices of buildings that receive direct sunlight. - Iterate through the list of buildings from left to right.
- For each building, check if its elevation is greater than or equal to the elevation of any subsequent building.
- If it is, add the current index to
sunlightReceiversand update the last index where we found a building that receives direct sunlight. - Return the length of
sunlightReceivers, which represents the number of buildings that receive direct sunlight.
Optimized Solutions
Java
public int countSunlightReceivers(int[] elevations) {
int sunlightReceivers = 0;
for (int i = 0; i < elevations.length; i++) {
boolean receivesDirectSunlight = true;
for (int j = i + 1; j < elevations.length; j++) {
if (elevations[i] <= elevations[j]) {
receivesDirectSunlight = false;
break;
}
}
if (receivesDirectSunlight) {
sunlightReceivers++;
}
}
return sunlightReceivers;
}