Open In App

Maximum people a person can see while standing in a line in both direction

Last Updated : 23 Jul, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Given an array height[] which represents the height of n people standing in a line. A person i can see a person j if height[j] < height[i] and there is no person k standing in between them such that height[k] >= height[i]. Find the maximum number of people a person can see.
Note: A person can see any other person irrespective of whether they are standing in his front or back.

Examples:

Input: heights[] = {6, 2, 5, 4, 5, 1, 6}.
Output: 6
Explanation:
Person 1 (height = 6) can see five other people at following positions (2, 3, 4, 5. 6) in addition to himself, i.e. total 6.
Person 2 (height: 2) can see only himself.
Person 3 (height = 5) is able to see people 2nd, 3rd, and 4th person.
Only Person 4 (height = 4) can see himself.
Person 5 (height = 5) can see people 4th, 5th, and 6th.
Person 6 (height =1) can only see himself.
Person 7 (height = 6) can see 2nd, 3rd, 4th, 5th, 6th, and 7th people.
A maximum of six people can be seen by Person 1, 7th

Input: heights[] = {1, 3, 6, 4}
Output: 3

[Naive Approach] Using Nested Loops - O(n^2) Time and O(1) Space

The idea is to determine how many people a person can see by checking both left and right directions separately. For each person, we iterate backward to count visible people on the left until we hit a taller height, and forward to count on the right similarly. The key observation is that a person can only see others shorter than them until a taller person blocks the view.

C++
// C++ Code to find the maximum number of people
// a person can see in both directions 
// using a naive approach
#include <bits/stdc++.h>
using namespace std;

// Function to find the maximum number of people
// a person can see in both directions
int maxPeople(vector<int>& height) {
    int n = height.size();
    int maxCount = 0;

    // Iterate through each person
    for (int i = 0; i < n; i++) {
        
         // Count the person itself
        int count = 1;
        int maxLeft = 0, maxRight = 0;

        // Check visibility towards the left
        for (int j = i - 1; j >= 0; j--) {
            if (height[j] > maxLeft) {
                count++;
                maxLeft = height[j];
            }
        }
        
        // Check visibility towards the right
        for (int j = i + 1; j < n; j++) {
            if (height[j] > maxRight) {
                count++;
                maxRight = height[j];
            }
        }
        
        // Update the maximum count
        maxCount = max(maxCount, count);
    }
    return maxCount;
}

int main() {

    vector<int> height = {6, 2, 5, 4, 5, 1, 6};
    
    cout<< maxPeople(height);

    return 0;
}
Java
// Java Code to find the maximum number of people
// a person can see in both directions 
// using a naive approach
import java.util.*;

class GfG {

    // Function to find the maximum number of people
    // a person can see in both directions
    static int maxPeople(int[] height) {
        int n = height.length;
        int maxCount = 0;

        // Iterate through each person
        for (int i = 0; i < n; i++) {
            
            // Count the person itself
            int count = 1;
            int maxLeft = 0, maxRight = 0;

            // Check visibility towards the left
            for (int j = i - 1; j >= 0; j--) {
                if (height[j] > maxLeft) {
                    count++;
                    maxLeft = height[j];
                }
            }
            
            // Check visibility towards the right
            for (int j = i + 1; j < n; j++) {
                if (height[j] > maxRight) {
                    count++;
                    maxRight = height[j];
                }
            }
            
            // Update the maximum count
            maxCount = Math.max(maxCount, count);
        }
        return maxCount;
    }

    public static void main(String[] args) {
        int[] height = {6, 2, 5, 4, 5, 1, 6};
        
        System.out.println(maxPeople(height));
    }
}
Python
# Python Code to find the maximum number of people
# a person can see in both directions 
# using a naive approach

# Function to find the maximum number of people
# a person can see in both directions
def maxPeople(height):
    n = len(height)
    max_count = 0

    # Iterate through each person
    for i in range(n):

        # Count the person itself
        count = 1
        max_left = 0
        max_right = 0

        # Check visibility towards the left
        for j in range(i - 1, -1, -1):
            if height[j] > max_left:
                count += 1
                max_left = height[j]

        # Check visibility towards the right
        for j in range(i + 1, n):
            if height[j] > max_right:
                count += 1
                max_right = height[j]

        # Update the maximum count
        max_count = max(max_count, count)

    return max_count

if __name__ == "__main__":
    height = [6, 2, 5, 4, 5, 1, 6]
    
    print(maxPeople(height))
C#
// C# Code to find the maximum number of people
// a person can see in both directions 
// using a naive approach
using System;

class GfG {
    
    // Function to find the maximum number of people
    // a person can see in both directions
    public static int maxPeople(int[] height) {
        int n = height.Length;
        int maxCount = 0;

        // Iterate through each person
        for (int i = 0; i < n; i++) {
            
            // Count the person itself
            int count = 1;
            int maxLeft = 0, maxRight = 0;

            // Check visibility towards the left
            for (int j = i - 1; j >= 0; j--) {
                if (height[j] > maxLeft) {
                    count++;
                    maxLeft = height[j];
                }
            }
            
            // Check visibility towards the right
            for (int j = i + 1; j < n; j++) {
                if (height[j] > maxRight) {
                    count++;
                    maxRight = height[j];
                }
            }
            
            // Update the maximum count
            maxCount = Math.Max(maxCount, count);
        }
        return maxCount;
    }

    public static void Main() {
        int[] height = {6, 2, 5, 4, 5, 1, 6};
        
        Console.WriteLine(maxPeople(height));
    }
}
JavaScript
// JavaScript Code to find the maximum number of people
// a person can see in both directions 
// using a naive approach

// Function to find the maximum number of people
// a person can see in both directions
function maxPeople(height) {
    let n = height.length;
    let maxCount = 0;

    // Iterate through each person
    for (let i = 0; i < n; i++) {
        
        // Count the person itself
        let count = 1;
        let maxLeft = 0, maxRight = 0;

        // Check visibility towards the left
        for (let j = i - 1; j >= 0; j--) {
            if (height[j] > maxLeft) {
                count++;
                maxLeft = height[j];
            }
        }
        
        // Check visibility towards the right
        for (let j = i + 1; j < n; j++) {
            if (height[j] > maxRight) {
                count++;
                maxRight = height[j];
            }
        }
        
        // Update the maximum count
        maxCount = Math.max(maxCount, count);
    }
    return maxCount;
}

// Driver code
let height = [6, 2, 5, 4, 5, 1, 6];

console.log(maxPeople(height));

Output
6

[Expected Approach] Using Monotonic Stack - O(n) Time and O(n) Space

If we take a closer look at this problem, we can notice that for every element, we need to find next greater (Closest greater element on right side) and previous greater (Closest greater on the left side). All the elements before next greater would be visible on the right side and all the elements after previous greater would be visible on the left side. We mainly implement the same stack idea as next greater and previous greater problems to find the next greater and previous greater for all elements in O(n) time. Finally, we return maximum of all values.

C++
// C++ Code to find max people visible in
// both directions using Monotonic Stack
#include <bits/stdc++.h>
using namespace std;

// Function to compute max people visible using stack
int maxPeople(vector<int>& height) {
    int n = height.size();
    
    // Initialize each person sees himself
    vector<int> left(n, 1), right(n, 1);  
    stack<int> st;

    // Compute left visibility using a decreasing stack
    for (int i = 0; i < n; i++) {
        while (!st.empty() && height[st.top()] < height[i]) {
            left[i] += left[st.top()];
            st.pop();
        }
        st.push(i);
    }

    // Clear stack for right computation
    while (!st.empty()) st.pop();

    // Compute right visibility using a decreasing stack
    for (int i = n - 1; i >= 0; i--) {
        while (!st.empty() && height[st.top()] < height[i]) {
            right[i] += right[st.top()];
            st.pop();
        }
        st.push(i);
    }

    // Find the max people visible
    int maxCount = 0;
    for (int i = 0; i < n; i++) {
        maxCount = max(maxCount, left[i] + right[i] - 1);
    }

    return maxCount;
}

int main() {
    vector<int> height = {6, 2, 5, 4, 5, 1, 6};
    cout << maxPeople(height);
    return 0;
}
Java
// Java Code to find max people visible in
// both directions using Monotonic Stack
import java.util.Stack;

class GfG {
    
    // Function to compute max people visible using stack
    static int maxPeople(int[] height) {
        int n = height.length;
        
        // Initialize each person sees himself
        int[] left = new int[n], right = new int[n];  
        for (int i = 0; i < n; i++) {
            left[i] = right[i] = 1;
        }
        Stack<Integer> st = new Stack<>();

        // Compute left visibility using a decreasing stack
        for (int i = 0; i < n; i++) {
            while (!st.isEmpty() && height[st.peek()] < height[i]) {
                left[i] += left[st.pop()];
            }
            st.push(i);
        }

        // Clear stack for right computation
        st.clear();

        // Compute right visibility using a decreasing stack
        for (int i = n - 1; i >= 0; i--) {
            while (!st.isEmpty() && height[st.peek()] < height[i]) {
                right[i] += right[st.pop()];
            }
            st.push(i);
        }

        // Find the max people visible
        int maxCount = 0;
        for (int i = 0; i < n; i++) {
            maxCount = Math.max(maxCount, left[i] + right[i] - 1);
        }

        return maxCount;
    }

    public static void main(String[] args) {
        int[] height = {6, 2, 5, 4, 5, 1, 6};
        System.out.println(maxPeople(height));
    }
}
Python
# Python Code to find max people visible in
# both directions using Monotonic Stack
def maxPeople(height):
    n = len(height)

    # Initialize each person sees himself
    left = [1] * n
    right = [1] * n  
    st = []

    # Compute left visibility using a decreasing stack
    for i in range(n):
        while st and height[st[-1]] < height[i]:
            left[i] += left[st.pop()]
        st.append(i)

    # Clear stack for right computation
    st.clear()

    # Compute right visibility using a decreasing stack
    for i in range(n - 1, -1, -1):
        while st and height[st[-1]] < height[i]:
            right[i] += right[st.pop()]
        st.append(i)

    # Find the max people visible
    maxCount = 0
    for i in range(n):
        maxCount = max(maxCount, left[i] + right[i] - 1)

    return maxCount

if __name__ == "__main__":
    
    height = [6, 2, 5, 4, 5, 1, 6]
    print(maxPeople(height))
C#
// C# Code to find max people visible in
// both directions using Monotonic Stack
using System;
using System.Collections.Generic;

class GfG {
    // Function to compute max people visible using stack
    public static int maxPeople(int[] height) {
        int n = height.Length;

        // Initialize each person sees himself
        int[] left = new int[n], right = new int[n];  
        for (int i = 0; i < n; i++) {
            left[i] = right[i] = 1;
        }
        Stack<int> st = new Stack<int>();

        // Compute left visibility using a decreasing stack
        for (int i = 0; i < n; i++) {
            while (st.Count > 0 && height[st.Peek()] < height[i]) {
                left[i] += left[st.Pop()];
            }
            st.Push(i);
        }

        // Clear stack for right computation
        st.Clear();

        // Compute right visibility using a decreasing stack
        for (int i = n - 1; i >= 0; i--) {
            while (st.Count > 0 && height[st.Peek()] < height[i]) {
                right[i] += right[st.Pop()];
            }
            st.Push(i);
        }

        // Find the max people visible
        int maxCount = 0;
        for (int i = 0; i < n; i++) {
            maxCount = Math.Max(maxCount, left[i] + right[i] - 1);
        }

        return maxCount;
    }

    public static void Main() {
        int[] height = {6, 2, 5, 4, 5, 1, 6};
        Console.WriteLine(maxPeople(height));
    }
}
JavaScript
// Javascript Code to find max people visible in
// both directions using Monotonic Stack
function maxPeople(height) {
    let n = height.length;

    // Initialize each person sees himself
    let left = new Array(n).fill(1);
    let right = new Array(n).fill(1);
    let st = [];

    // Compute left visibility using a decreasing stack
    for (let i = 0; i < n; i++) {
        while (st.length > 0 && height[st[st.length - 1]] < height[i]) {
            left[i] += left[st.pop()];
        }
        st.push(i);
    }

    // Clear stack for right computation
    st = [];

    // Compute right visibility using a decreasing stack
    for (let i = n - 1; i >= 0; i--) {
        while (st.length > 0 && height[st[st.length - 1]] < height[i]) {
            right[i] += right[st.pop()];
        }
        st.push(i);
    }

    // Find the max people visible
    let maxCount = 0;
    for (let i = 0; i < n; i++) {
        maxCount = Math.max(maxCount, left[i] + right[i] - 1);
    }

    return maxCount;
}

let height = [6, 2, 5, 4, 5, 1, 6];
console.log(maxPeople(height));

Output
6

Further Optimization

We can further optimize the above code to wok using single for loop only. Please refer Largest Area in a Histogram problem fore reference.



Article Tags :

Similar Reads