📌  相关文章
📜  数组元素的数量大于其左侧的所有元素以及其右侧的下一个K元素

📅  最后修改于: 2021-04-29 13:23:45             🧑  作者: Mango

给定数组arr [] ,任务是打印大于其左侧所有元素以及大于其右侧下一个K元素的元素数量。

例子:

天真的方法:
遍历数组,对于每个元素,检查其左侧的所有元素是否均小于其,以及其右侧的下一个K元素是否均小于其。对于每个这样的元素,增加count 。最后,打印计数

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

高效方法:
通过使用堆栈数据结构可以优化上述方法。请按照以下步骤解决问题:

  1. 初始化一个新数组,并使用Stack为每个数组元素存储Next Greater Element的索引。
  2. 遍历给定数组,并为每个元素检查到目前为止是否获得最大的数组,并且其下一个更大的元素至少是当前索引之后的K个索引。如果发现是真的,请增加count
  3. 最后,打印计数

下面是上述方法的实现:

C++
// C++ Program to implement
// the above approach
#include 
using namespace std;
  
// Function to print the count of
// Array elements greater than all
// elemnts on its left and next K
// elements on its right
int countElements(int arr[], int n,
                  int k)
{
  
    stack s;
  
    vector next_greater(n, n + 1);
  
    // Iterate over the array
    for (int i = 0; i < n; i++) {
  
        if (s.empty()) {
            s.push(i);
            continue;
        }
  
        // If the stack is not empty and
        // the element at the top of the
        // stack is smaller than arr[i]
        while (!s.empty()
               && arr[s.top()] < arr[i]) {
            // Store the index of next
            // greater element
            next_greater[s.top()] = i;
  
            // Pop the top element
            s.pop();
        }
  
        // Insert the current index
        s.push(i);
    }
  
    // Stores the count
    int count = 0;
    int maxi = INT_MIN;
    for (int i = 0; i < n; i++) {
        if (next_greater[i] - i > k
            && maxi < arr[i]) {
            maxi = max(maxi, arr[i]);
            count++;
        }
    }
  
    return count;
}
  
// Driver Code
int main()
{
  
    int arr[] = { 4, 2, 3, 6, 4, 3, 2 };
    int K = 2;
    int n = sizeof(arr) / sizeof(arr[0]);
    cout << countElements(arr, n, K);
  
    return 0;
}


Java
// Java program to implement
// the above approach
import java.util.*;
  
class GFG{
  
// Function to print the count of
// Array elements greater than all
// elemnts on its left and next K
// elements on its right
static int countElements(int arr[], int n,
                                    int k)
{
    Stack s = new Stack();
  
    int []next_greater = new int[n + 1];
    Arrays.fill(next_greater, n);
  
    // Iterate over the array
    for(int i = 0; i < n; i++)
    {
        if (s.isEmpty())
        {
            s.add(i);
            continue;
        }
  
        // If the stack is not empty and
        // the element at the top of the
        // stack is smaller than arr[i]
        while (!s.isEmpty() && 
               arr[s.peek()] < arr[i]) 
        {
              
            // Store the index of next
            // greater element
            next_greater[s.peek()] = i;
  
            // Pop the top element
            s.pop();
        }
  
        // Insert the current index
        s.add(i);
    }
  
    // Stores the count
    int count = 0;
    int maxi = Integer.MIN_VALUE;
      
    for(int i = 0; i < n; i++) 
    {
        if (next_greater[i] - i > k && 
              maxi < arr[i])
        {
            maxi = Math.max(maxi, arr[i]);
            count++;
        }
    }
    return count;
}
  
// Driver Code
public static void main(String[] args)
{
    int arr[] = { 4, 2, 3, 6, 4, 3, 2 };
    int K = 2;
    int n = arr.length;
      
    System.out.print(countElements(arr, n, K));
}
}
  
// This code is contributed by PrinciRaj1992


Python3
# Python3 program to implement
# the above approach
import sys
  
# Function to print the count of
# Array elements greater than all
# elemnts on its left and next K
# elements on its right
def countElements(arr, n, k):
  
    s = []
  
    next_greater = [n] * (n + 1)
  
    # Iterate over the array
    for i in range(n):
        if(len(s) == 0):
            s.append(i)
            continue
  
        # If the stack is not empty and
        # the element at the top of the
        # stack is smaller than arr[i]
        while(len(s) != 0 and
              arr[s[-1]] < arr[i]):
                    
            # Store the index of next
            # greater element
            next_greater[s[-1]] = i
  
            # Pop the top element
            s.pop(-1)
  
        # Insert the current index
        s.append(i)
  
    # Stores the count 
    count = 0
    maxi = -sys.maxsize - 1
      
    for i in range(n):
        if(next_greater[i] - i > k and
             maxi < arr[i]):
            maxi = max(maxi, arr[i])
            count += 1
  
    return count
  
# Driver Code
if __name__ == '__main__':
  
    arr = [ 4, 2, 3, 6, 4, 3, 2 ]
    K = 2
    n = len(arr)
  
    # Function call
    print(countElements(arr, n, K))
  
# This code is contributed by Shivam Singh


C#
// C# program to implement
// the above approach
using System;
using System.Collections.Generic;
  
class GFG{
      
// Function to print the count of 
// Array elements greater than all 
// elemnts on its left and next K 
// elements on its right 
static int countElements(int[] arr, int n,
                         int k) 
{ 
    Stack s = new Stack(); 
  
    int[] next_greater = new int[n + 1]; 
    Array.Fill(next_greater, n); 
  
    // Iterate over the array 
    for(int i = 0; i < n; i++) 
    { 
        if (s.Count == 0) 
        { 
            s.Push(i); 
            continue; 
        } 
  
        // If the stack is not empty and 
        // the element at the top of the 
        // stack is smaller than arr[i] 
        while (s.Count != 0 && 
               arr[s.Peek()] < arr[i]) 
        { 
              
            // Store the index of next 
            // greater element 
            next_greater[s.Peek()] = i; 
  
            // Pop the top element 
            s.Pop(); 
        } 
  
        // Insert the current index 
        s.Push(i); 
    } 
  
    // Stores the count 
    int count = 0; 
    int maxi = Int32.MinValue; 
      
    for(int i = 0; i < n; i++) 
    { 
        if (next_greater[i] - i > k && 
                       maxi < arr[i]) 
        { 
            maxi = Math.Max(maxi, arr[i]); 
            count++; 
        } 
    } 
    return count; 
} 
  
// Driver Code
static void Main()
{
    int[] arr = { 4, 2, 3, 6, 4, 3, 2 }; 
    int K = 2; 
    int n = arr.Length; 
  
    Console.Write(countElements(arr, n, K));
}
} 
  
// This code is contributed by divyeshrabadiya07


输出:
2

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