Count of numbers in given Array greater than next K elements
Last Updated :
11 May, 2022
Given an array arr[] of integers of size N, the task is to count the number of elements whose value is greater than all the K elements to its immediate right. If there are less than K numbers to the right of the ith element, then the value of all of them must be lesser than that of the ith person.
Examples:
Input: arr[] = {4, 3, 1, 2, 5}, N = 5, K = 1
Output: 3
Explanation: The 1st ,2nd and 5th are the elements whose values are greater than the element to its right(As k = 1 consider only the next). While the 3rd element can not be considered because of the 4th element whose value is greater than the 3rd element’s value.
Input: arr[] = {9, 7, 7, 7, 4}, N = 5, K = 3
Output: 3
Explanation: The 1st ,4th and the 5th element will be the elements whose values are greater than all 3 elements after it.
Naive Approach: For each element check K elements to their immediate right and see if it is greater than all of those or not.
Time Complexity: O(N2)
Auxiliary Space: O(1)
Efficient Approach: This problem can be solved using the following steps:
- Consider a queue for storing K elements.
- Add K elements from the last to the queue and keep the max of the last K values in a variable (say, max_value).
- Iterate over the remaining array in the backward direction from the position (N – K).
- While iterating pop an element from the queue and push the current element in the queue.
- If the current element has a value greater than max_value, then increment the count and update max_value to the current element.
- Else If the popped value is the same as the max_value then find the new max from the queue.
- Return the count value as the count of the element whose value is greater than all the k elements to its immediate right.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int find_max(queue< int > q)
{
int ans = INT_MIN;
while (!q.empty()) {
ans = max(ans, q.front());
q.pop();
}
return ans;
}
int solve( int n, int k, vector< int > arr)
{
int max_value = INT_MIN;
queue< int > q;
int count = 0;
int p = n - k;
if (n == 0)
return 0;
else if (k == 0)
return n;
for ( int i = n - 1; i >= p; i--) {
q.push(arr[i]);
if (arr[i] > max_value) {
max_value = arr[i];
count++;
}
}
for ( int i = p - 1; i >= 0; i--) {
int x = q.front();
q.pop();
q.push(arr[i]);
if (arr[i] > max_value) {
count++;
max_value = arr[i];
}
else {
if (x == max_value) {
max_value = find_max(q);
}
}
}
return count;
}
int main()
{
int N, K;
N = 5;
K = 1;
vector< int > arr = { 4, 3, 1, 2, 5};
cout << solve(N, K, arr) << "\n" ;
return 0;
}
|
Java
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Queue;
class GFG {
public static int find_max(Queue<Integer> q) {
int ans = Integer.MIN_VALUE;
while (!q.isEmpty()) {
ans = Math.max(ans, q.peek());
q.remove();
}
return ans;
}
public static int solve( int n, int k, ArrayList<Integer> arr) {
int max_value = Integer.MIN_VALUE;
Queue<Integer> q = new LinkedList<Integer>();
int count = 0 ;
int p = n - k;
if (n == 0 )
return 0 ;
else if (k == 0 )
return n;
for ( int i = n - 1 ; i >= p; i--) {
q.add(arr.get(i));
if (arr.get(i) > max_value) {
max_value = arr.get(i);
count++;
}
}
for ( int i = p - 1 ; i >= 0 ; i--) {
int x = 0 ;
if (q.size() > 0 ) {
x = q.peek();
q.remove();
}
q.add(arr.get(i));
if (arr.get(i) > max_value) {
count++;
max_value = arr.get(i);
} else {
if (x == max_value) {
max_value = find_max(q);
}
}
}
return count;
}
public static void main(String args[]) {
int N, K;
N = 5 ;
K = 1 ;
ArrayList<Integer> arr = new ArrayList<>();
arr.add( 4 );
arr.add( 3 );
arr.add( 1 );
arr.add( 2 );
arr.add( 5 );
System.out.println(solve(N, K, arr));
}
}
|
Python3
from queue import Queue
import copy
INT_MIN = - 2147483648
def find_max(q):
ans = INT_MIN
while ( not q.empty()):
ans = max (ans, q.get())
return ans
def solve(n, k, arr):
max_value = INT_MIN
q = Queue()
count = 0
p = n - k
if (n = = 0 ):
return 0
elif (k = = 0 ):
return n
for i in range (n - 1 , p - 1 , - 1 ):
q.put(arr[i])
if (arr[i] > max_value):
max_value = arr[i]
count + = 1
for i in range (p - 1 , - 1 , - 1 ):
x = q.get()
q.put(arr[i])
if (arr[i] > max_value):
count + = 1
max_value = arr[i]
else :
if (x = = max_value):
temp = Queue()
for i in q.queue:
temp.put(i)
max_value = find_max(temp)
return count
if __name__ = = "__main__" :
N = 5
K = 1
arr = [ 4 , 3 , 1 , 2 , 5 ]
print (solve(N, K, arr))
|
C#
using System;
using System.Collections.Generic;
public class GFG {
public static int find_max(Queue< int > q) {
int ans = int .MinValue;
while (q.Count != 0) {
ans = Math.Max(ans, q.Peek());
q.Dequeue();
}
return ans;
}
public static int solve( int n, int k, List< int > arr) {
int max_value = int .MinValue;
Queue< int > q = new Queue< int >();
int count = 0;
int p = n - k;
if (n == 0)
return 0;
else if (k == 0)
return n;
for ( int i = n - 1; i >= p; i--) {
q.Enqueue(arr[i]);
if (arr[i] > max_value) {
max_value = arr[i];
count++;
}
}
for ( int i = p - 1; i >= 0; i--) {
int x = 0;
if (q.Count > 0) {
x = q.Peek();
q.Dequeue();
}
q.Enqueue(arr[i]);
if (arr[i] > max_value) {
count++;
max_value = arr[i];
} else {
if (x == max_value) {
max_value = find_max(q);
}
}
}
return count;
}
public static void Main(String []args) {
int N, K;
N = 5;
K = 1;
List< int > arr = new List< int >();
arr.Add(4);
arr.Add(3);
arr.Add(1);
arr.Add(2);
arr.Add(5);
Console.WriteLine(solve(N, K, arr));
}
}
|
Javascript
<script>
function find_max(q) {
let ans = Number.MIN_SAFE_INTEGER;
while (q.length) {
ans = Math.max(ans, q[0]);
q.pop();
}
return ans;
}
function solve(n, k, arr) {
let max_value = Number.MIN_SAFE_INTEGER;
let q = [];
let count = 0;
let p = n - k;
if (n == 0)
return 0;
else if (k == 0)
return n;
for (let i = n - 1; i >= p; i--) {
q.push(arr[i]);
if (arr[i] > max_value) {
max_value = arr[i];
count++;
}
}
for (let i = p - 1; i >= 0; i--) {
let x = q[0];
q.pop();
q.push(arr[i]);
if (arr[i] > max_value) {
count++;
max_value = arr[i];
}
else {
if (x == max_value) {
max_value = find_max(q);
}
}
}
return count;
}
let N, K;
N = 5;
K = 1;
let arr = [4, 3, 1, 2, 5];
document.write(solve(N, K, arr))
</script>
|
Time Complexity: O(N)
Auxiliary Space: O(K)
Space Optimized Approach: The problem can be solved with lesser space using two pointer approach. Follow the steps mentioned below.
- Initialize two-pointer (say “left” and “right”) pointing to the end of the array.
- The left pointer points to the starting index of the K-sized window and the right pointer points to the maximum value in that window.
- If the value at the left pointer is greater than the value at the right pointer, increase answer count by 1. (Because it means it is greater than all the K elements to its immediate right)
- If at any point the window size exceeds K, decrement the right pointer by one and adjust it to point to the maximum value of the current window.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int solve( int n, int k, vector< int > arr)
{
int count = 1;
int left = n - 2, right = n - 1;
if (n == 0)
return 0;
else if (k == 0)
return n;
for (; left >= 0; left--) {
if (right - left > k) {
right--;
while (arr[left] > arr[right])
right--;
if (right == left)
count++;
}
else if (arr[left] > arr[right]) {
count++;
right = left;
}
}
return count;
}
int main()
{
int N, K;
N = 5;
K = 1;
vector< int > arr = { 4, 3, 1, 2, 5};
cout << solve(N, K, arr);
return 0;
}
|
Java
import java.io.*;
class GFG{
static int solve( int n, int k, int [] arr)
{
int count = 1 ;
int left = n - 2 , right = n - 1 ;
if (n == 0 )
return 0 ;
else if (k == 0 )
return n;
for (; left >= 0 ; left--)
{
if (right - left > k)
{
right--;
while (arr[left] > arr[right])
right--;
if (right == left)
count++;
}
else if (arr[left] > arr[right])
{
count++;
right = left;
}
}
return count;
}
public static void main(String[] args)
{
int N, K;
N = 5 ;
K = 1 ;
int [] arr = { 4 , 3 , 1 , 2 , 5 };
System.out.println(solve(N, K, arr));
}
}
|
Python3
def solve(n, k, arr):
count = 1
left = n - 2
right = n - 1
if (n = = 0 ):
return 0
elif (k = = 0 ):
return n
while left > = 0 :
if (right - left > k):
right - = 1
while (arr[left] > arr[right]):
right - = 1
if (right = = left):
count + = 1
elif (arr[left] > arr[right]):
count + = 1
right = left
left - = 1
return count
if __name__ = = "__main__" :
N = 5
K = 1
arr = [ 4 , 3 , 1 , 2 , 5 ]
print (solve(N, K, arr))
|
C#
using System;
public class GFG
{
static int solve( int n, int k, int [] arr)
{
int count = 1;
int left = n - 2, right = n - 1;
if (n == 0)
return 0;
else if (k == 0)
return n;
for (; left >= 0; left--)
{
if (right - left > k)
{
right--;
while (arr[left] > arr[right])
right--;
if (right == left)
count++;
}
else if (arr[left] > arr[right])
{
count++;
right = left;
}
}
return count;
}
public static void Main(String[] args)
{
int N, K;
N = 5;
K = 1;
int [] arr = { 4, 3, 1, 2, 5 };
Console.WriteLine(solve(N, K, arr));
}
}
|
Javascript
<script>
function solve(n , k, arr)
{
var count = 1;
var left = n - 2, right = n - 1;
if (n == 0)
return 0;
else if (k == 0)
return n;
for (; left >= 0; left--)
{
if (right - left > k)
{
right--;
while (arr[left] > arr[right])
right--;
if (right == left)
count++;
}
else if (arr[left] > arr[right])
{
count++;
right = left;
}
}
return count;
}
var N, K;
N = 5;
K = 1;
var arr = [ 4, 3, 1, 2, 5 ];
document.write(solve(N, K, arr));
</script>
|
Time Complexity: O(N)
Auxiliary Space: O(1)
Share your thoughts in the comments
Please Login to comment...