To Find count of buildings that receive sunlight

Share

Problem: You will be given buildings of certain height that lie adjacent to each other . Sun starts falling from left side. If there is a building of certain Height, all the buildings right of it having lesser heights cannot see the sun . You need to find the total number of such buildings that receive sunlight.

Problem Explanation: You are given an array a = {6, 2, 8, 4, 11, 13 }, this means you are given with six buildings with corresponding heights. So, for this input the result will be 4

Java Implementation



public void countDesiredBuildings(int arr[]) {
    int maxEle = arr[0];
    int count =1;
    
    for(int i=1;i<arr.length;i++){
        if(arr[i]>maxEle){
            count++;
            maxEle = arr[i];
        }
    }
    System.out.println("Count of building that receive sunlight:" + count);
}
TimeComplexity: O(n)

Note: If you find any other better way to approach to this problem or you find any issue/error in above code snippets/approaches – please share it in the comments section below and get a chance to enrol free of cost for an online Live Data Structure and Algorithm course (specially designed for interview preparation for software companies like Amazon, Google, Facebook, FlipKart, SnapDeal, HealthKart…)