Elements before which no element is bigger in array
Given an array of integers, the task is to find the count of elements before which all the elements are smaller. The first element is always counted as there is no other element before it.
Examples:
Input : arr[] = {10, 40, 23, 35, 50, 7}
Output : 3
The elements are 10, 40 and 50.
Input : arr[] = {5, 4, 1}
Output : 1
A Naive approach is to one by one consider an element and check with all the previous elements. If an element is greater than all, increment the result.
An Efficient method is to store the maximum value in the array at each index and if the next element is greater than maximum value increment the result and update maximum with that element.
Below is implementation of this method.
C++
#include <bits/stdc++.h>
using namespace std;
int countElements( int arr[], int n)
{
int result = 1;
int max_ele = arr[0];
for ( int i = 1; i < n; i++) {
if (arr[i] > max_ele) {
max_ele = arr[i];
result++;
}
}
return result;
}
int main()
{
int arr[] = { 10, 40, 23, 35, 50, 7 };
int n = sizeof (arr) / sizeof (arr[0]);
cout << countElements(arr, n);
return 0;
}
|
Java
class Test {
static int countElements( int arr[], int n)
{
int result = 1 ;
int max_ele = arr[ 0 ];
for ( int i = 1 ; i < n; i++) {
if (arr[i] > max_ele) {
max_ele = arr[i];
result++;
}
}
return result;
}
public static void main(String[] args)
{
int arr[] = { 10 , 40 , 23 , 35 , 50 , 7 };
System.out.println(countElements(arr, arr.length));
}
}
|
Python 3
def countElements(arr, n):
result = 1
max_ele = arr[ 0 ]
for i in range ( 1 , n ):
if (arr[i] > max_ele):
max_ele = arr[i]
result + = 1
return result
arr = [ 10 , 40 , 23 ,
35 , 50 , 7 ]
n = len (arr)
print (countElements(arr, n))
|
C#
using System;
class GFG {
static int countElements( int [] arr, int n)
{
int result = 1;
int max_ele = arr[0];
for ( int i = 1; i < n; i++) {
if (arr[i] > max_ele) {
max_ele = arr[i];
result++;
}
}
return result;
}
public static void Main()
{
int [] arr = { 10, 40, 23, 35, 50, 7 };
Console.WriteLine(countElements(arr, arr.Length));
}
}
|
PHP
<?php
function countElements( $arr , $n )
{
$result = 1;
$max_ele = $arr [0];
for ( $i = 1; $i < $n ; $i ++)
{
if ( $arr [ $i ] > $max_ele )
{
$max_ele = $arr [ $i ];
$result ++;
}
}
return $result ;
}
$arr = array (10, 40, 23, 35, 50, 7);
$n = sizeof( $arr );
echo countElements( $arr , $n );
?>
|
Javascript
<script>
function countElements(arr, n)
{
let result = 1;
let max_ele = arr[0];
for (let i = 1; i < n; i++) {
if (arr[i] > max_ele) {
max_ele = arr[i];
result++;
}
}
return result;
}
let arr = [ 10, 40, 23, 35, 50, 7 ];
document.write(countElements(arr, arr.length));
</script>
|
Time Complexity : O(n),where n is a number of elements in input.
Auxiliary Space : O(1)
Last Updated :
11 Sep, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...