📜  一个人在两个方向排成一排时能看到的最大人数

📅  最后修改于: 2022-05-13 01:56:07.909000             🧑  作者: Mango

一个人在两个方向排成一排时能看到的最大人数

给定一个数组height[] ,它代表N个人站在一条直线上的高度。一个人i可以看到一个人j如果height[j] < height[i]并且没有人k站在他们之间,这样height[j] ≥ height[i] 。找出一个人可以看到的最大人数。

注意:一个人可以看到任何其他人,无论他们是站在他的前面还是后面。

例子:

天真的方法:一个简单的解决方案是遍历给定的数组和行中的每个idx

  • 维护一个指向idx-1的左指针(leftptr ) 和一个指向idx+1的右指针(rightptr)
  • 将左指针向左移动,直到找到身高大于或等于height[idx]的人。
  • 向右移动右指针,直到找到身高大于或等于身高 [idx]的人。
  • 左右指针索引之间的差异为我们提供了第 i个人可以看到的人数并将Ans更新为max(Ans, rightptr – leftptr-1)

下面是上述思想的实现。

C++
// C++ code to implement the above approach
#include 
using namespace std;
 
// Function to find the leftmost index
// of the person whose height is
// greater the height of person idx.
int leftindex(vector heights,
              int idx, int n)
{
 
    int h = heights[idx];
    for (int i = idx - 1; i >= 0; i--) {
 
        // If height of person i is
        // greater than or equal to
        // current person of height h
        // then the current person(idx)
        // cannot see him
        if (heights[i] >= h)
            return i;
    }
    // If a person can see all other people
    // who are standing on his left
    return -1;
}
 
// Function to find the rightmost index
// of the person whose height is
// greater the height of person idx.
int rightindex(vector heights,
               int idx, int n)
{
    int h = heights[idx];
    for (int i = idx + 1; i < n; i++) {
 
        // If height of person i is
        // greater than or equal to
        // current person of height h
        // then the current person(idx)
        // cannot see him
        if (heights[i] >= h)
            return i;
    }
    // If a person can see all other people
    // who are standing on his right
    return n;
}
 
// Function to find maximum number of people
// a person can see
int max_people(vector heights, int n)
{
    // Ans stores the maximum of people
    // a person can see
    int ans = 0;
    for (int i = 0; i < n; i++) {
 
        // Leftptr stores the leftmost index
        // of the person which
        // the current person cannot see
        int leftptr
            = leftindex(heights, i, n);
 
        // Rightptr stores the rightmost index
        // of the person which
        // the current person cannot see
        int rightptr
            = rightindex(heights, i, n);
 
        // Maximum number of people
        // a person can see
        ans = max(ans,
                  rightptr - leftptr - 1);
    }
    return ans;
}
 
// Driver code
int main()
{
    int N = 7;
    vector heights{ 6, 2, 5, 4, 5, 1, 6 };
 
    // Function call
    cout << max_people(heights, N) << endl;
    return 0;
}


Java
// JAVA code to implement the above approach
import java.util.*;
class GFG
{
 
  // Function to find the leftmost index
  // of the person whose height is
  // greater the height of person idx.
  public static int leftindex(int[] heights, int idx,
                              int n)
  {
 
    int h = heights[idx];
    for (int i = idx - 1; i >= 0; i--) {
 
      // If height of person i is
      // greater than or equal to
      // current person of height h
      // then the current person(idx)
      // cannot see him
      if (heights[i] >= h)
        return i;
    }
    // If a person can see all other people
    // who are standing on his left
    return -1;
  }
 
  // Function to find the rightmost index
  // of the person whose height is
  // greater the height of person idx.
  public static int rightindex(int[] heights, int idx,
                               int n)
  {
    int h = heights[idx];
    for (int i = idx + 1; i < n; i++) {
 
      // If height of person i is
      // greater than or equal to
      // current person of height h
      // then the current person(idx)
      // cannot see him
      if (heights[i] >= h)
        return i;
    }
 
    // If a person can see all other people
    // who are standing on his right
    return n;
  }
 
  // Function to find maximum number of people
  // a person can see
  public static int max_people(int[] heights, int n)
  {
 
    // Ans stores the maximum of people
    // a person can see
    int ans = 0;
    for (int i = 0; i < n; i++) {
 
      // Leftptr stores the leftmost index
      // of the person which
      // the current person cannot see
      int leftptr = leftindex(heights, i, n);
 
      // Rightptr stores the rightmost index
      // of the person which
      // the current person cannot see
      int rightptr = rightindex(heights, i, n);
 
      // Maximum number of people
      // a person can see
      ans = Math.max(ans, rightptr - leftptr - 1);
    }
    return ans;
  }
 
  // Driver code
  public static void main(String[] args)
  {
    int N = 7;
    int[] heights = new int[] { 6, 2, 5, 4, 5, 1, 6 };
 
    // Function call
    System.out.println(max_people(heights, N));
  }
}
 
// This code is contributed by Taranpreet


Python3
# Python code to implement the above approach
 
# Function to find the leftmost index
# of the person whose height is
# greater the height of person idx.
def leftindex(heights, idx,  n):
    h = heights[idx]
    for i in range(idx - 1, -1, -1):
 
        # If height of person i is
        # greater than or equal to
        # current person of height h
        # then the current person(idx)
        # cannot see him
        if heights[i] >= h:
            return i
 
    # If a person can see all other people
    # who are standing on his left
    return -1
 
# Function to find the rightmost index
# of the person whose height is
# greater the height of person idx.
def rightindex(heights, idx,  n):
 
    h = heights[idx]
    for i in range(idx + 1, n):
       
        # If height of person i is
        # greater than or equal to
        # current person of height h
        # then the current person(idx)
        # cannot see him
        if (heights[i] >= h):
            return i
 
    # If a person can see all other people
    # who are standing on his right
    return n
 
# Function to find maximum number of people
# a person can see
def max_people(heights,  n):
 
    # Ans stores the maximum of people
    # a person can see
    ans = 0
    for i in range(n):
       
        # Leftptr stores the leftmost index
        # of the person which
        # the current person cannot see
        leftptr = leftindex(heights, i, n)
         
        # Rightptr stores the rightmost index
        # of the person which
        # the current person cannot see
        rightptr = rightindex(heights, i, n)
 
        # Maximum number of people
        # a person can see
        ans = max(ans, rightptr - leftptr - 1)
 
    return ans
 
# Driver code
N = 7
heights=[6, 2, 5, 4, 5, 1, 6]
 
# Function call
print(max_people(heights, N))
 
# This code is contributed by rohitsingh07052.


C#
// C# code to implement the above approach
using System;
class GFG
{
 
  // Function to find the leftmost index
  // of the person whose height is
  // greater the height of person idx.
  static int leftindex(int[] heights, int idx,
                       int n)
  {
 
    int h = heights[idx];
    for (int i = idx - 1; i >= 0; i--) {
 
      // If height of person i is
      // greater than or equal to
      // current person of height h
      // then the current person(idx)
      // cannot see him
      if (heights[i] >= h)
        return i;
    }
    // If a person can see all other people
    // who are standing on his left
    return -1;
  }
 
  // Function to find the rightmost index
  // of the person whose height is
  // greater the height of person idx.
  static int rightindex(int[] heights, int idx,
                        int n)
  {
    int h = heights[idx];
    for (int i = idx + 1; i < n; i++) {
 
      // If height of person i is
      // greater than or equal to
      // current person of height h
      // then the current person(idx)
      // cannot see him
      if (heights[i] >= h)
        return i;
    }
 
    // If a person can see all other people
    // who are standing on his right
    return n;
  }
 
  // Function to find maximum number of people
  // a person can see
  static int max_people(int[] heights, int n)
  {
 
    // Ans stores the maximum of people
    // a person can see
    int ans = 0;
    for (int i = 0; i < n; i++) {
 
      // Leftptr stores the leftmost index
      // of the person which
      // the current person cannot see
      int leftptr = leftindex(heights, i, n);
 
      // Rightptr stores the rightmost index
      // of the person which
      // the current person cannot see
      int rightptr = rightindex(heights, i, n);
 
      // Maximum number of people
      // a person can see
      ans = Math.Max(ans, rightptr - leftptr - 1);
    }
    return ans;
  }
 
  // Driver code
  public static void Main()
  {
    int N = 7;
    int[] heights = new int[] { 6, 2, 5, 4, 5, 1, 6 };
 
    // Function call
    Console.WriteLine(max_people(heights, N));
  }
}
 
// This code is contributed by Samim Hossain Mondal.


Javascript


C++
// C++ code to implement the above approach
#include 
using namespace std;
 
// Function to store the index
// of next taller person on left
void leftindex(vector heights,
               vector& l_heights,
               int n)
{
    stack st;
 
    for (int i = 0; i < n; i++) {
        // While the top value of the stack
        // is lesser than the
        // current person's height
        while (st.empty() == false
               && heights[st.top()]
                      < heights[i])
            st.pop();
 
        // If the stack is empty
        l_heights[i]
            = (st.empty() == false)
                  ? st.top()
                  : (-1);
        st.push(i);
    }
 
    return;
}
 
// Function to store the index of
// next taller person on right
void rightindex(vector& heights,
                vector& r_heights,
                int n)
{
    // Stack to store the next
    // taller person on its right
    stack st;
 
    for (int i = n - 1; i >= 0; i--) {
 
        // If the top value of the stack
        // is lesser than the current height
        while (st.empty() == false
               && heights[st.top()]
                      < heights[i])
            st.pop();
 
        // If the stack is empty
        r_heights[i]
            = (st.empty() == false)
                  ? st.top()
                  : n;
        st.push(i);
    }
    return;
}
 
// Function to find the maximum number
// of people a person can see
int max_people(vector heights, int n)
{
    // To store the answer
    int ans = 0;
 
    vector r_heights(n), l_heights(n);
    leftindex(heights, l_heights, n);
    rightindex(heights, r_heights, n);
    for (int i = 0; i < n; i++) {
 
        // Contains the leftmost index
        // of the person which
        // current person cannot see
        int l_index = l_heights[i];
 
        // Contains the rightmost index
        // of the person which
        // the current person cannot see
        int r_index = r_heights[i];
 
        // Calculate the maximum answer
        ans = max(ans, r_index - l_index - 1);
    }
    return ans;
}
 
// Driver code
int main()
{
    int N = 7;
    vector heights{ 6, 2, 5, 4, 5, 1, 6 };
 
    // Function call
    cout << max_people(heights, N) << endl;
    return 0;
}


Python3
# Python code to implement the above approach
 
# Function to store the index
# of next taller person on left
def leftindex(heights, l_heights, n):
    st = []
    for i in range(n):
       
        # While the top value of the stack
        # is lesser than the
        # current person's height
        while (st != [] and heights[st[-1]] < heights[i]):
            st.pop()
             
        # If the stack is empty
        if st:
            l_heights[i] = st[-1]
        else:
              l_heights[i] = -1
        st.append(i)
    return l_heights
 
# Function to store the index of
# next taller person on right
def rightindex(heights, r_heights, n):
   
    # Stack to store the next
    # taller person on its right
    st = []
 
    for i in range(n - 1, -1, -1):
       
        # If the top value of the stack
        # is lesser than the current height
        while (st != [] and heights[st[-1]] < heights[i]):
            st.pop()
             
        # If the stack is empty
        if st:
              r_heights[i] = st[-1]
        else:
              r_heights[i] = n
        st.append(i)
     
    return r_heights
 
# Function to find the maximum number
# of people a person can see
def max_people( heights,  n):
   
      # To store the answer
    ans = 0
    r_heights=[0 for i in range(n)]
    l_heights= [0 for i in range(n)]
    l_heights = leftindex(heights, l_heights, n)
    r_heights = rightindex(heights, r_heights, n)
    for i in range(n):
       
        # Contains the leftmost index
        # of the person which
        # current person cannot see
        l_index = l_heights[i]
         
        # Contains the rightmost index
        # of the person which
        # the current person cannot see
        r_index = r_heights[i]
         
        # Calculate the maximum answer
        ans = max(ans, r_index - l_index - 1)
    return ans
 
# Driver code
N = 7
heights = [6, 2, 5, 4, 5, 1, 6 ]
 
# Function call
print(max_people(heights, N))
 
# This code is contributed by rohitsingh07052.


Javascript


输出
6

时间复杂度: O(N 2 )
辅助空间: O(N)

有效的方法:这个问题可以使用stacks来解决。对于行中的每个人,我们都试图在右边找到下一个较高的人的索引,在左边找到下一个较高的人的索引。

  • 创建一个大小为N的数组r_heights来存储下一个更大的人(右)的索引。
  • 要找到右边下一个大人物的位置:
  • 将数组的最后一个索引压入堆栈。
  • 对于从N-1 到 0 的每个索引:
  • 继续从堆栈中弹出索引,直到找到一个高度大于或等于当前人的高度的索引,或者直到堆栈为空。
  • 如果堆栈不为空,则更新r_heights[i]值以匹配堆栈顶部,否则r_heights[i]=N。
  • 将当前索引压入堆栈。
  • 0 迭代到 N以找到行中每个人左侧的下一个更大的人的索引。
  • 对于行中的每个人,他可以看到的人数是r_heigths[i]-l_heights[i]-1 。将 Ans 更新为max(Ans, r_heigths[i]-l_heigths[i]-1)

以下是上述方法的实现:

C++

// C++ code to implement the above approach
#include 
using namespace std;
 
// Function to store the index
// of next taller person on left
void leftindex(vector heights,
               vector& l_heights,
               int n)
{
    stack st;
 
    for (int i = 0; i < n; i++) {
        // While the top value of the stack
        // is lesser than the
        // current person's height
        while (st.empty() == false
               && heights[st.top()]
                      < heights[i])
            st.pop();
 
        // If the stack is empty
        l_heights[i]
            = (st.empty() == false)
                  ? st.top()
                  : (-1);
        st.push(i);
    }
 
    return;
}
 
// Function to store the index of
// next taller person on right
void rightindex(vector& heights,
                vector& r_heights,
                int n)
{
    // Stack to store the next
    // taller person on its right
    stack st;
 
    for (int i = n - 1; i >= 0; i--) {
 
        // If the top value of the stack
        // is lesser than the current height
        while (st.empty() == false
               && heights[st.top()]
                      < heights[i])
            st.pop();
 
        // If the stack is empty
        r_heights[i]
            = (st.empty() == false)
                  ? st.top()
                  : n;
        st.push(i);
    }
    return;
}
 
// Function to find the maximum number
// of people a person can see
int max_people(vector heights, int n)
{
    // To store the answer
    int ans = 0;
 
    vector r_heights(n), l_heights(n);
    leftindex(heights, l_heights, n);
    rightindex(heights, r_heights, n);
    for (int i = 0; i < n; i++) {
 
        // Contains the leftmost index
        // of the person which
        // current person cannot see
        int l_index = l_heights[i];
 
        // Contains the rightmost index
        // of the person which
        // the current person cannot see
        int r_index = r_heights[i];
 
        // Calculate the maximum answer
        ans = max(ans, r_index - l_index - 1);
    }
    return ans;
}
 
// Driver code
int main()
{
    int N = 7;
    vector heights{ 6, 2, 5, 4, 5, 1, 6 };
 
    // Function call
    cout << max_people(heights, N) << endl;
    return 0;
}

Python3

# Python code to implement the above approach
 
# Function to store the index
# of next taller person on left
def leftindex(heights, l_heights, n):
    st = []
    for i in range(n):
       
        # While the top value of the stack
        # is lesser than the
        # current person's height
        while (st != [] and heights[st[-1]] < heights[i]):
            st.pop()
             
        # If the stack is empty
        if st:
            l_heights[i] = st[-1]
        else:
              l_heights[i] = -1
        st.append(i)
    return l_heights
 
# Function to store the index of
# next taller person on right
def rightindex(heights, r_heights, n):
   
    # Stack to store the next
    # taller person on its right
    st = []
 
    for i in range(n - 1, -1, -1):
       
        # If the top value of the stack
        # is lesser than the current height
        while (st != [] and heights[st[-1]] < heights[i]):
            st.pop()
             
        # If the stack is empty
        if st:
              r_heights[i] = st[-1]
        else:
              r_heights[i] = n
        st.append(i)
     
    return r_heights
 
# Function to find the maximum number
# of people a person can see
def max_people( heights,  n):
   
      # To store the answer
    ans = 0
    r_heights=[0 for i in range(n)]
    l_heights= [0 for i in range(n)]
    l_heights = leftindex(heights, l_heights, n)
    r_heights = rightindex(heights, r_heights, n)
    for i in range(n):
       
        # Contains the leftmost index
        # of the person which
        # current person cannot see
        l_index = l_heights[i]
         
        # Contains the rightmost index
        # of the person which
        # the current person cannot see
        r_index = r_heights[i]
         
        # Calculate the maximum answer
        ans = max(ans, r_index - l_index - 1)
    return ans
 
# Driver code
N = 7
heights = [6, 2, 5, 4, 5, 1, 6 ]
 
# Function call
print(max_people(heights, N))
 
# This code is contributed by rohitsingh07052.

Javascript


输出
6

时间复杂度 O(N)
辅助空间 O(N)