|
| 1 | +package Stack; |
| 2 | + |
| 3 | +public class Maximumpeople { |
| 4 | + |
| 5 | + public static int leftindex(int[] heights, int idx, |
| 6 | + int n) |
| 7 | + { |
| 8 | + |
| 9 | + int h = heights[idx]; |
| 10 | + for (int i = idx - 1; i >= 0; i--) { |
| 11 | + |
| 12 | + // If height of person i is |
| 13 | + // greater than or equal to |
| 14 | + // current person of height h |
| 15 | + // then the current person(idx) |
| 16 | + // cannot see him |
| 17 | + if (heights[i] >= h) |
| 18 | + return i; |
| 19 | + } |
| 20 | + // If a person can see all other people |
| 21 | + // who are standing on his left |
| 22 | + return -1; |
| 23 | + } |
| 24 | + |
| 25 | + public static int rightindex(int[] heights, int idx, |
| 26 | + int n) |
| 27 | +{ |
| 28 | +int h = heights[idx]; |
| 29 | +for (int i = idx + 1; i < n; i++) { |
| 30 | + |
| 31 | +// If height of person i is |
| 32 | +// greater than or equal to |
| 33 | +// current person of height h |
| 34 | +// then the current person(idx) |
| 35 | +// cannot see him |
| 36 | +if (heights[i] >= h) |
| 37 | +return i; |
| 38 | +} |
| 39 | + |
| 40 | +// If a person can see all other people |
| 41 | +// who are standing on his right |
| 42 | +return n; |
| 43 | +} |
| 44 | + |
| 45 | + public static int max_people(int[] heights, int n) |
| 46 | + { |
| 47 | + |
| 48 | + // Ans stores the maximum of people |
| 49 | + // a person can see |
| 50 | + int ans = 0; |
| 51 | + for (int i = 0; i < n; i++) { |
| 52 | + |
| 53 | + // Leftptr stores the leftmost index |
| 54 | + // of the person which |
| 55 | + // the current person cannot see |
| 56 | + int leftptr = leftindex(heights, i, n); |
| 57 | + |
| 58 | + // Rightptr stores the rightmost index |
| 59 | + // of the person which |
| 60 | + // the current person cannot see |
| 61 | + int rightptr = rightindex(heights, i, n); |
| 62 | + |
| 63 | + // Maximum number of people |
| 64 | + // a person can see |
| 65 | + ans = Math.max(ans, rightptr - leftptr - 1); |
| 66 | + } |
| 67 | + return ans; |
| 68 | + } |
| 69 | + public static void main(String[] args) { |
| 70 | + int N = 7; |
| 71 | + int[] heights = new int[] { 6, 2, 5, 4, 5, 1, 6 }; |
| 72 | + |
| 73 | + // Function call |
| 74 | + System.out.println(max_people(heights, N)); |
| 75 | + } |
| 76 | +} |
0 commit comments