Given an array of integers, consider the elements as the height of the building, find the number of buildings that can be seen from the right side.
Examples:
Input : height[] = {2, 6, 2, 4, 0, 1}
Output : 3
we can see only 3 building i.e with height 1, 4 and 6.
Input : height[] = {4, 8, 2, 0, 0, 5}
Output : 2
This problem seems to be finding longest increasing sub sequence from right but actually it is not.We have to just increase the count if we encounter any building with greater height found so far.
Below is the implementation of above approach.
C++
#include <bits/stdc++.h>
using namespace std;
int numberOfElements(int height[], int n)
{
int max_so_far = 0;
int coun = 0;
for (int i = n - 1; i >= 0; i--) {
if (height[i] > max_so_far) {
max_so_far = height[i];
coun++;
}
}
return coun;
}
int main()
{
int n = 6;
int height[] = { 4, 8, 2, 0, 0, 5 };
cout << numberOfElements(height, n);
return 0;
}
|
Java
import java.util.*;
class Solution
{
static int numberOfElements(int height[], int n)
{
int max_so_far = 0;
int coun = 0;
for (int i = n - 1; i >= 0; i--) {
if (height[i] > max_so_far) {
max_so_far = height[i];
coun++;
}
}
return coun;
}
public static void main(String args[])
{
int n = 6;
int height[] = { 4, 8, 2, 0, 0, 5 };
System.out.println( numberOfElements(height, n));
}
}
|
Python3
def numberOfElements(height, n):
max_so_far = 0
coun = 0
for i in range(n-1,-1,-1):
if height[i] > max_so_far:
max_so_far = height[i]
coun = coun + 1
return coun
if __name__=='__main__':
n = 6
height = [4, 8, 2, 0, 0, 5]
print(numberOfElements(height, n))
|
C#
using System;
class GFG
{
public static int numberOfElements(int []height,
int n)
{
int max_so_far = 0;
int coun = 0;
for (int i = n - 1; i >= 0; i--)
{
if (height[i] > max_so_far)
{
max_so_far = height[i];
coun++;
}
}
return coun;
}
public static void Main()
{
int n = 6;
int []height = { 4, 8, 2, 0, 0, 5 };
Console.WriteLine(numberOfElements(height, n));
}
}
|
PHP
<?php
function numberOfElements($height, $n)
{
$max_so_far = 0;
$coun = 0;
for ($i = $n - 1; $i >= 0; $i--)
{
if ($height[$i] > $max_so_far)
{
$max_so_far = $height[$i];
$coun++;
}
}
return $coun;
}
$n = 6;
$height = array(4, 8, 2, 0, 0, 5 );
echo numberOfElements($height, $n);
|
Javascript
<script>
function numberOfElements(height , n)
{
var max_so_far = 0;
var coun = 0;
for (let i = n - 1; i >= 0; i--)
{
if (height[i] > max_so_far)
{
max_so_far = height[i];
coun++;
}
}
return coun;
}
var n = 6;
var height = [ 4, 8, 2, 0, 0, 5 ];
document.write(numberOfElements(height, n));
</script>
|