数组中局部极值数的Python程序
您将获得一个包含 n 个元素的数组。极值是大于其两个邻居或小于其两个邻居的元素。您必须计算给定数组中的局部极值数。
注意:第一个和最后一个元素不是极值。
例子 :
Input : a[] = {1, 5, 2, 5}
Output : 2
Input : a[] = {1, 2, 3}
Output : 0
方法:为了计算极值的数量,我们必须检查一个元素是最大值还是最小值,即它是大于它的两个邻居还是小于两个邻居。为此,只需遍历数组并为每个元素检查其成为极值的可能性。
注意: a[0] 和 a[n-1] 分别只有一个邻居,它们既不是最小值也不是最大值。
Python3
# Python 3 to find
# number of extrema
# function to find
# local extremum
def extrema(a, n):
count = 0
# start loop from
# position 1 till n-1
for i in range(1, n - 1) :
# only one condition
# will be true
# at a time either
# a[i] will be greater
# than neighbours or
# less than neighbours
# check if a[i] if
# greater than both its
# neighbours, then add
# 1 to x
count += (a[i] > a[i - 1] and a[i] > a[i + 1]);
# check if a[i] if
# less than both its
# neighbours, then
# add 1 to x
count += (a[i] < a[i - 1] and a[i] < a[i + 1]);
return count
# driver program
a = [1, 0, 2, 1 ]
n = len(a)
print(extrema(a, n))
# This code is contributed by Smitha Dinesh Semwal
输出 :
2
有关详细信息,请参阅有关数组中局部极值数的完整文章!