计算数组双调性的程序
给定一个数组整数。任务是找到给定数组的双调性。
数组 arr[] 的双调性可以定义为:
B[i] = 0, if i = 0.
= B[i-1] + 1, if arr[i] > arr[i-1]
= B[i-1] - 1, if arr[i] < arr[i-1]
= B[i-1], if arr[i] = arr[i-1]
Bitonicity will be last element of array B[].
例子:
Input : arr[] = {1, 2, 3, 4, 5}
Output : 4
Input : arr[] = {1, 4, 5, 3, 2}
Output : 0
鉴于数组 arr[] 的双调性可以定义为:
B[i] = 0, if i = 0.
= B[i-1] + 1, if arr[i] > arr[i-1]
= B[i-1] - 1, if arr[i] < arr[i-1]
= B[i-1], if arr[i] = arr[i-1]
Bitonicity will be last element of array B[].
由上式可以推导出:
- 数组的双调性最初为 0。
- 如果下一个元素大于前一个元素,则它在移动到下一个元素时增加 1。
- 如果下一个元素大于前一个元素,则在移动到下一个元素时它减 1。
这个想法是采取一个变量并开始遍历数组,如果下一个元素大于当前,则将bt加 1,如果下一个元素小于当前,则将bt减 1。
下面是上述方法的实现:
C++
// C++ program to find bitonicity
// of an array
#include
using namespace std;
// Function to find the bitonicity
// of an array
int findBitonicity(int arr[], int n)
{
int bt = 0;
for (int i = 1; i < n; i++) {
if (arr[i] > arr[i - 1])
bt++;
else if (arr[i] < arr[i - 1])
bt--;
}
return bt;
}
// Driver Code
int main()
{
int arr[] = { 1, 2, 3, 4, 5, 6, 4, 3 };
int n = sizeof(arr) / sizeof(arr[0]);
cout << "Bitonicity = " << findBitonicity(arr, n);
return 0;
}
Java
// Java program to find bitonicity
// of an array
import java.util.*;
import java.lang.*;
class GFG
{
// Function to find the bitonicity
// of an array
static int findBitonicity(int[] arr,
int n)
{
int bt = 0;
for (int i = 1; i < n; i++)
{
if (arr[i] > arr[i - 1])
bt++;
else if (arr[i] < arr[i - 1])
bt--;
}
return bt;
}
// Driver Code
public static void main(String args[])
{
int arr[] = { 1, 2, 3, 4, 5, 6, 4, 3 };
int n = arr.length;
System.out.print("Bitonicity = " +
findBitonicity(arr, n));
}
}
// This code is contributed
// by Akanksha Rai
Python3
# Python3 program to find bitonicity
# of an array
# Function to find the bitonicity
# of an array
def findBitonicity(arr, n):
bt = 0
for i in range(1, n, 1):
if (arr[i] > arr[i - 1]):
bt += 1
elif (arr[i] < arr[i - 1]):
bt -= 1
return bt
# Driver Code
if __name__ == '__main__':
arr = [1, 2, 3, 4, 5, 6, 4, 3]
n = len(arr)
print("Bitonicity =",
findBitonicity(arr, n))
# This code is contributed by
# Surendra_Gangwar
C#
// C# program to find bitonicity
// of an array
using System;
class GFG
{
// Function to find the bitonicity
// of an array
static int findBitonicity(int[] arr,
int n)
{
int bt = 0;
for (int i = 1; i < n; i++)
{
if (arr[i] > arr[i - 1])
bt++;
else if (arr[i] < arr[i - 1])
bt--;
}
return bt;
}
// Driver Code
public static void Main()
{
int[] arr = { 1, 2, 3, 4, 5, 6, 4, 3 };
int n = arr.Length;
Console.Write("Bitonicity = " +
findBitonicity(arr, n));
}
}
// This code is contributed
// by Akanksha Rai
PHP
$arr[$i - 1])
$bt++;
else if ($arr[$i] < $arr[$i - 1])
$bt--;
}
return $bt;
}
// Driver Code
$arr = array(1, 2, 3, 4, 5, 6, 4, 3 );
$n = sizeof($arr);
echo ("Bitonicity = ");
echo findBitonicity($arr, $n);
// This code is contributed
// by Shivi_Aggarwal
?>
Javascript
输出:
Bitonicity = 3