Count of indices in an array that satisfy the given condition
Given an array arr[] of N positive integers, the task is to find the count of indices i such that all the elements from arr[0] to arr[i – 1] are smaller than arr[i].
Examples:
Input: arr[] = {1, 2, 3, 4}
Output: 4
All indices satisfy the given condition.
Input: arr[] = {4, 3, 2, 1}
Output: 1
Only i = 0 is the valid index.
Approach: The idea is to traverse the array from left to right and keep track of the current maximum, whenever this maximum changes then the current index is a valid index so increment the resulting counter.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int countIndices( int arr[], int n)
{
int cnt = 0;
int max = 0;
for ( int i = 0; i < n; i++) {
if (max < arr[i]) {
max = arr[i];
cnt++;
}
}
return cnt;
}
int main()
{
int arr[] = { 1, 2, 3, 4 };
int n = sizeof (arr) / sizeof ( int );
cout << countIndices(arr, n);
return 0;
}
|
Java
class GFG
{
static int countIndices( int arr[], int n)
{
int cnt = 0 ;
int max = 0 ;
for ( int i = 0 ; i < n; i++)
{
if (max < arr[i])
{
max = arr[i];
cnt++;
}
}
return cnt;
}
public static void main(String[] args)
{
int arr[] = { 1 , 2 , 3 , 4 };
int n = arr.length;
System.out.println(countIndices(arr, n));
}
}
|
Python3
def countIndices(arr, n):
cnt = 0 ;
max = 0 ;
for i in range (n):
if ( max < arr[i]):
max = arr[i];
cnt + = 1 ;
return cnt;
if __name__ = = '__main__' :
arr = [ 1 , 2 , 3 , 4 ];
n = len (arr);
print (countIndices(arr, n));
|
C#
using System;
class GFG
{
static int countIndices( int []arr, int n)
{
int cnt = 0;
int max = 0;
for ( int i = 0; i < n; i++)
{
if (max < arr[i])
{
max = arr[i];
cnt++;
}
}
return cnt;
}
public static void Main(String[] args)
{
int []arr = { 1, 2, 3, 4 };
int n = arr.Length;
Console.WriteLine(countIndices(arr, n));
}
}
|
Javascript
<script>
function countIndices(arr , n) {
var cnt = 0;
var max = 0;
for (i = 0; i < n; i++) {
if (max < arr[i]) {
max = arr[i];
cnt++;
}
}
return cnt;
}
var arr = [ 1, 2, 3, 4 ];
var n = arr.length;
document.write(countIndices(arr, n));
</script>
|
Time Complexity: O(n)
Auxiliary Space: O(1)
Last Updated :
01 Mar, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...