,  

Number of buildings facing the Sun

Problem: The heights of the building is given in an array. Buildings are facing the sun. You have to tell which all buildings will see the sunset. It is assumed that heights of all buildings are distinct.
For example:
Input : arr[] = {7, 4, 8, 2, 9}
Output: 3

4 can't see the sunset as 7 is hiding it. 
8 can see.
2 can't see the sunset.
9 also can see the sunset.
Method 1: Seeing the above picture we can say that only the maximum element found so far will see the sunlight i.e. curr_max will see the sunlight and then only the element greater than curr_max will see the sunlight. The algorithm is:
  1. Traverse given array from left to right.
  2. Keep track of maximum element seen so far
  3. Whenever an element becomes more than current max, increment result and update current max.
class InterviewDesk
{
    /* method to return count of buildings that 
       can see the sunlight */
    static int buildingCount(int height[], int n)
    {
        /* initial the result. The first building will
           always see the sunlight */
        int count = 1;
      
        int curr_max = height[0];
        for (int i=1; i curr_max)
            {
                count++;
                curr_max=height[i];
            }
        }
      
        /* return the result */
        return count;
    }
     
    // Driver method
    public static void main(String[] args) 
    {
        int height[] = {7, 4, 8, 2, 9};
         
        System.out.println(buildingCount(height, height.length));
    }
}
Output:
3
Time Complexity: O(n)