给定一个数组Arr [] 。任务是计算给定数组中元素Arr [i]的数量,以使一个或多个较小的元素出现在数组中元素Arr [i]的右侧。
例子:
Input: Arr[] = { 3, 9, 4, 6, 7, 5 }
Output: 3
Numbers that counts are: 9, 6, 7
9 – As all numbers are present after 9 are smaller than 9,
6 – 5 is smaller element present after it,
7 – 5 is smaller element which is present after it.
Input: Arr[] = { 3, 2, 1, 2, 3, 4, 5 }
Output: 2
方法:
从数组的最后一个元素开始遍历数组。遍历时,请保留一个min变量和一个counter变量,该变量存储到目前为止的最小元素。将min变量与当前元素进行比较。如果min变量小于当前元素Arr [i] ,则增加计数器;如果min大于Arr [i],则更新min 。
下面是上述方法的实现:
C++
// C++ implementation
#include
using namespace std;
// function to return the count
int count_greater(int arr[], int n)
{
int min = INT_MAX;
int counter = 0;
// Comparing the given element
// with minimum element till
// occurred till now.
for (int i = n - 1; i >= 0; i--) {
if (arr[i] > min) {
counter++;
}
// Updating the min variable
if (arr[i] <= min) {
min = arr[i];
}
}
return counter;
}
// Driver code
int main()
{
int arr[] = { 3, 2, 1, 2, 3, 4, 5 };
int n = sizeof(arr) / sizeof(int);
cout << count_greater(arr, n) << endl;
return 0;
}
Java
// Java implementation of the approach
class GFG
{
// function to return the count
static int count_greater(int arr[], int n)
{
int min = Integer.MAX_VALUE;
int counter = 0;
// Comparing the given element
// with minimum element till
// occurred till now.
for (int i = n - 1; i >= 0; i--)
{
if (arr[i] > min)
{
counter++;
}
// Updating the min variable
if (arr[i] <= min)
{
min = arr[i];
}
}
return counter;
}
// Driver code
public static void main(String[] args)
{
int arr[] = { 3, 2, 1, 2, 3, 4, 5 };
int n = arr.length;
System.out.println(count_greater(arr, n));
}
}
// This code is contributed by 29AjayKumar
Python3
# Python3 implementation for the above approach
import sys
# function to return the count
def count_greater(arr, n) :
min = sys.maxsize;
counter = 0;
# Comparing the given element
# with minimum element till
# occurred till now.
for i in range(n - 1, -1, -1) :
if (arr[i] > min) :
counter += 1;
# Updating the min variable
if (arr[i] <= min) :
min = arr[i];
return counter;
# Driver code
if __name__ == "__main__" :
arr = [ 3, 2, 1, 2, 3, 4, 5 ];
n = len(arr);
print(count_greater(arr, n));
# This code is contributed by AnkitRai01
C#
// C# implementation of the approach
using System;
class GFG
{
// function to return the count
static int count_greater(int []arr, int n)
{
int min = int.MaxValue;
int counter = 0;
// Comparing the given element
// with minimum element till
// occurred till now.
for (int i = n - 1; i >= 0; i--)
{
if (arr[i] > min)
{
counter++;
}
// Updating the min variable
if (arr[i] <= min)
{
min = arr[i];
}
}
return counter;
}
// Driver code
static public void Main ()
{
int []arr = { 3, 2, 1, 2, 3, 4, 5 };
int n = arr.Length;
Console.Write(count_greater(arr, n));
}
}
// This code is contributed by ajit.
输出:
2