Count positions such that all elements before it are greater
Given an array A[], the task is to find the number of positions i in the array such that all elements before A[i] are greater than A[i].
Note: First element is always counted as there is no other element before it.
Examples:
Input: N = 4, A[] = {2, 1, 3, 5}
Output: 2
The valid positions are 1, 2.
Input : N = 3, A[] = {7, 6, 5}
Output: 3
All three positions are valid positions.
The idea is to calculate the minimum element every time while traversing the array. That is:
- Initialize the first element as the minimum element.
- Every time a new element arrives, check if this is the new minimum, if so, increment number of valid positions and also initialize minimum to the new minimum.
Below is the implementation of the above approach:
CPP
#include <bits/stdc++.h>
using namespace std;
int getPositionCount( int a[], int n)
{
int count = 1;
int min = a[0];
for ( int i=1; i<n; i++)
{
if (a[i] <= min)
{
min = a[i];
count++;
}
}
return count;
}
int main()
{
int a[] = { 5, 4, 6, 1, 3, 1 };
int n = sizeof (a) / sizeof (a[0]);
cout<<getPositionCount(a, n);
return 0;
}
|
Java
class GFG
{
static int getPositionCount( int a[], int n)
{
int count = 1 ;
int min = a[ 0 ];
for ( int i = 1 ; i < n; i++)
{
if (a[i] <= min)
{
min = a[i];
count++;
}
}
return count;
}
public static void main(String[] args)
{
int a[] = { 5 , 4 , 6 , 1 , 3 , 1 };
int n = a.length;
System.out.print(getPositionCount(a, n));
}
}
|
Python3
def getPositionCount(a, n) :
count = 1 ;
min = a[ 0 ];
for i in range ( 1 , n) :
if (a[i] < = min ) :
min = a[i];
count + = 1 ;
return count;
if __name__ = = "__main__" :
a = [ 5 , 4 , 6 , 1 , 3 , 1 ];
n = len (a);
print (getPositionCount(a, n));
|
C#
using System;
class GFG
{
static int getPositionCount( int []a, int n)
{
int count = 1;
int min = a[0];
for ( int i = 1; i < n; i++)
{
if (a[i] <= min)
{
min = a[i];
count++;
}
}
return count;
}
public static void Main()
{
int []a = { 5, 4, 6, 1, 3, 1 };
int n = a.Length;
Console.WriteLine(getPositionCount(a, n));
}
}
|
Javascript
<script>
function getPositionCount(a, n)
{
var count = 1;
var min = a[0];
for ( var i = 1; i < n; i++)
{
if (a[i] <= min)
{
min = a[i];
count++;
}
}
return count;
}
var a = [5, 4, 6, 1, 3, 1];
var n = a.length;
document.write( getPositionCount(a, n));
</script>
|
Time Complexity: O(N)
Last Updated :
16 Jun, 2021
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...