Number of element that can be seen from right side.

Problem :  Number of element that can be seen from right side.
                 Given an array of integers, consider the elements as the height of the building, find the number of buildings that can be seen from right side.

Explanation : In the Given Array {2,6,2,4,0,1} from right side 3 numbers (6,4,1)are in increasing order so these all can be visible from right side. So result will be 3.
Same in this array{ 4,8,2,0,0,5 } result will be 2 (8,5), 5 will hide  0,0,2 and 8 will hide 4 so only 2 can be visible.

public class VisibleBuildings {
public static void main(String[] args) {
int[] arr = {2,6,2,4,0,1};
//int[] arr = { 4,8,2,0,0,5 };
System.out.println(getVisibleBuilding(arr));
}

private static int getVisibleBuilding(int[] arr) {
if(arr.length == 1 ) {
return 1;
}else if(arr.length == 2) {
if(arr[0]>arr[1]) {
return 2;
}else {
return 1;
}
}
int[] ar = new int[arr.length];
ar[0] = 1;
boolean temp = true;
for (int i = 1; i < arr.length; i++) {
for (int j = 0; j <= i; j++) {
if (arr[j] < arr[i]) {
ar[j] = 0;
}else if(arr[j] != arr[i]) {
temp = false;
}
else {
ar[i] = 1;
}
}
}
if(temp) {
return 1;
}
int big = Integer.MAX_VALUE;
int bigIndex = 0;
//System.out.println(Arrays.toString(ar));
int result = ar[0];
for (int i = 1; i < ar.length; i++) {
if (ar[i] == 1 && arr[i] < big) {
ar[i] = ar[bigIndex] + 1;
big = arr[i];
bigIndex = i;
if(result < ar[i]) result =ar[i];
}
}
//System.out.println(Arrays.toString(ar));
return result;
}
}





Post a Comment

Previous Post Next Post