There exists a bulit-in function argrelextrema that gets this task done:
import numpy as np
from scipy.signal import argrelextrema
a = np.array([1,2,3,4,5,4,3,2,1,2,3,2,1,2,3,4,5,6,5,4,3,2,1])
# determine the indices of the local maxima
max_ind = argrelextrema(a, np.greater)
# get the actual values using these indices
r = a[max_ind] # array([5, 3, 6])
That gives you the desired output for r.
As of SciPy version 1.1, you can also use find_peaks. Below are two examples taken from the documentation itself.
Using the height argument, one can select all maxima above a certain threshold (in this example, all non-negative maxima; this can be very useful if one has to deal with a noisy baseline; if you want to find minima, just multiply you input by -1):
import matplotlib.pyplot as plt
from scipy.misc import electrocardiogram
from scipy.signal import find_peaks
import numpy as np
x = electrocardiogram()[2000:4000]
peaks, _ = find_peaks(x, height=0)
plt.plot(x)
plt.plot(peaks, x[peaks], "x")
plt.plot(np.zeros_like(x), "--", color="gray")
plt.show()
Another extremely helpful argument is distance, which defines the minimum distance between two peaks:
peaks, _ = find_peaks(x, distance=150)
# difference between peaks is >= 150
print(np.diff(peaks))
# prints [186 180 177 171 177 169 167 164 158 162 172]
plt.plot(x)
plt.plot(peaks, x[peaks], "x")
plt.show()
Improve Article
Save Article
Like Article
Improve Article
Save Article
Like Article
Given an array arr[] of integers. The task is to find the indices of all local minima and local maxima in the given array.
Examples:
Input: arr = [100, 180, 260, 310, 40, 535, 695]
Output:
Points of local minima: 0 4
Points of local maxima: 3 6
Explanation:
Given array can be break as below sub-arrays:
1. first sub array
[100, 180, 260, 310]
index of local minima = 0
index of local maxima = 3
2. second sub array
[40, 535, 695]
index of local minima = 4
index of local maxima = 6Input: arr = [23, 13, 25, 29, 33, 19, 34, 45, 65, 67]
Output:
Points of local minima: 1 5
Points of local maxima: 0 4 9
Approach: The idea is to iterate over the given array arr[] and check if each element of the array is smallest or greatest among their adjacent element. If it is smallest then it is local minima and if it is greatest then it is local maxima. Below are the steps:
- Create two arrays max[] and min[] to store all the local maxima and local minima.
- Traverse the given array and append the index of the array into the array max[] and min[] according to the below conditions:
- If arr[i – 1] > arr[i] < arr[i + 1] then append that index to min[].
- If arr[i – 1] < arr[i] > arr[i + 1] then append that index to max[].
- Check for the local maxima and minima conditions for the first and last elements separately.
- Print the indexes stored in min[] and max[].
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
void findLocalMaximaMinima(int n, int arr[])
{
vector<int> mx, mn;
if (arr[0] > arr[1])
mx.push_back(0);
else if (arr[0] < arr[1])
mn.push_back(0);
for(int i = 1; i < n - 1; i++)
{
if ((arr[i - 1] > arr[i]) and
(arr[i] < arr[i + 1]))
mn.push_back(i);
else if ((arr[i - 1] < arr[i]) and
(arr[i] > arr[i + 1]))
mx.push_back(i);
}
if (arr[n - 1] > arr[n - 2])
mx.push_back(n - 1);
else if (arr[n - 1] < arr[n - 2])
mn.push_back(n - 1);
if (mx.size() > 0)
{
cout << "Points of Local maxima are : ";
for(int a : mx)
cout << a << " ";
cout << endl;
}
else
cout << "There are no points of "
<< "Local Maxima n";
if (mn.size() > 0)
{
cout << "Points of Local minima are : ";
for(int a : mn)
cout << a << " ";
cout << endl;
}
else
cout << "There are no points of "
<< "Local Minima n";
}
int main()
{
int N = 9;
int arr[] = { 10, 20, 15, 14, 13,
25, 5, 4, 3 };
findLocalMaximaMinima(N, arr);
return 0;
}
Java
import java.util.*;
class GFG{
public static void findLocalMaximaMinima(int n,
int[] arr)
{
Vector<Integer> mx = new Vector<Integer>();
Vector<Integer> mn = new Vector<Integer>();
if (arr[0] > arr[1])
mx.add(0);
else if (arr[0] < arr[1])
mn.add(0);
for(int i = 1; i < n - 1; i++)
{
if ((arr[i - 1] > arr[i]) &&
(arr[i] < arr[i + 1]))
mn.add(i);
else if ((arr[i - 1] < arr[i]) &&
(arr[i] > arr[i + 1]))
mx.add(i);
}
if (arr[n - 1] > arr[n - 2])
mx.add(n - 1);
else if (arr[n - 1] < arr[n - 2])
mn.add(n - 1);
if (mx.size() > 0)
{
System.out.print("Points of Local " +
"maxima are : ");
for(Integer a : mx)
System.out.print(a + " ");
System.out.println();
}
else
System.out.println("There are no points " +
"of Local Maxima ");
if (mn.size() > 0)
{
System.out.print("Points of Local " +
"minima are : ");
for(Integer a : mn)
System.out.print(a + " ");
System.out.println();
}
else
System.out.println("There are no points of " +
"Local Maxima ");
}
public static void main(String[] args)
{
int N = 9;
int arr[] = { 10, 20, 15, 14, 13,
25, 5, 4, 3 };
findLocalMaximaMinima(N, arr);
}
}
Python3
def findLocalMaximaMinima(n, arr):
mx = []
mn = []
if(arr[0] > arr[1]):
mx.append(0)
elif(arr[0] < arr[1]):
mn.append(0)
for i in range(1, n-1):
if(arr[i-1] > arr[i] < arr[i + 1]):
mn.append(i)
elif(arr[i-1] < arr[i] > arr[i + 1]):
mx.append(i)
if(arr[-1] > arr[-2]):
mx.append(n-1)
elif(arr[-1] < arr[-2]):
mn.append(n-1)
if(len(mx) > 0):
print("Points of Local maxima"
" are : ", end ='')
print(*mx)
else:
print("There are no points of"
" Local maxima.")
if(len(mn) > 0):
print("Points of Local minima"
" are : ", end ='')
print(*mn)
else:
print("There are no points"
" of Local minima.")
if __name__ == '__main__':
N = 9
arr = [10, 20, 15, 14, 13, 25, 5, 4, 3]
findLocalMaximaMinima(N, arr)
C#
using System;
using System.Collections;
using System.Collections.Generic;
class GFG{
public static void findLocalMaximaMinima(int n,
int[] arr)
{
ArrayList mx = new ArrayList();
ArrayList mn = new ArrayList();
if (arr[0] > arr[1])
mx.Add(0);
else if (arr[0] < arr[1])
mn.Add(0);
for(int i = 1; i < n - 1; i++)
{
if ((arr[i - 1] > arr[i]) &&
(arr[i] < arr[i + 1]))
mn.Add(i);
else if ((arr[i - 1] < arr[i]) &&
(arr[i] > arr[i + 1]))
mx.Add(i);
}
if (arr[n - 1] > arr[n - 2])
mx.Add(n - 1);
else if (arr[n - 1] < arr[n - 2])
mn.Add(n - 1);
if (mx.Count > 0)
{
Console.Write("Points of Local " +
"maxima are : ");
foreach(int a in mx)
Console.Write(a + " ");
Console.Write("n");
}
else
Console.Write("There are no points " +
"of Local Maxima ");
if (mn.Count > 0)
{
Console.Write("Points of Local " +
"minima are : ");
foreach(int a in mn)
Console.Write(a + " ");
Console.Write("n");
}
else
Console.Write("There are no points of " +
"Local Maxima ");
}
public static void Main(string[] args)
{
int N = 9;
int []arr = { 10, 20, 15, 14, 13,
25, 5, 4, 3 };
findLocalMaximaMinima(N, arr);
}
}
Javascript
<script>
function findLocalMaximaMinima(n, arr)
{
let mx = [], mn = [];
if (arr[0] > arr[1])
mx.push(0);
else if (arr[0] < arr[1])
mn.push(0);
for(let i = 1; i < n - 1; i++)
{
if ((arr[i - 1] > arr[i]) &&
(arr[i] < arr[i + 1]))
mn.push(i);
else if ((arr[i - 1] < arr[i]) &&
(arr[i] > arr[i + 1]))
mx.push(i);
}
if (arr[n - 1] > arr[n - 2])
mx.push(n - 1);
else if (arr[n - 1] < arr[n - 2])
mn.push(n - 1);
if (mx.length > 0)
{
document.write("Points of Local maxima are : ");
for(let a of mx){
document.write(a," ");
}
document.write("</br>");
}
else
document.write("There are no points of Local Maxima ","</br>");
if (mn.length > 0)
{
document.write("Points of Local minima are : ");
for(let a of mn){
document.write(a," ");
}
document.write("</br>");
}
else
document.write("There are no points of Local Minima","</br>");
}
let N = 9;
let arr = [ 10, 20, 15, 14, 13, 25, 5, 4, 3 ];
findLocalMaximaMinima(N, arr);
</script>
Output:
Points of Local maxima are : 1 5 Points of Local minima are : 0 4 8
Time Complexity: O(N)
Auxiliary Space: O(N)
Last Updated :
08 Mar, 2022
Like Article
Save Article
Vote for difficulty
Current difficulty :
Medium
|
1 / 1 / 0 Регистрация: 16.10.2011 Сообщений: 45 |
|
|
1 |
|
Вывести все локальные максимумы массива29.10.2011, 10:49. Показов 9100. Ответов 7
Доброго времени суток ! Вот задача: ввести длину массива и массив типа инт. Вывести все локальные максимумы (локальный максимум — это элемент массива, который имеет значение больше чем его правый и левый сосед) Заранее спасибо !
0 |
|
amor1k Студент 148 / 148 / 64 Регистрация: 18.01.2011 Сообщений: 469 |
||||
|
29.10.2011, 10:58 |
2 |
|||
|
правильно?
0 |
|
1 / 1 / 0 Регистрация: 16.10.2011 Сообщений: 45 |
|
|
29.10.2011, 11:15 [ТС] |
3 |
|
Я уже набросал программу. Код такой же как у вас, но у вас ест ошибки.
0 |
|
2554 / 1319 / 178 Регистрация: 09.05.2011 Сообщений: 3,086 Записей в блоге: 1 |
|
|
29.10.2011, 11:24 |
4 |
|
0 |
|
wind_mill 1 / 1 / 0 Регистрация: 16.10.2011 Сообщений: 45 |
||||
|
29.10.2011, 15:37 [ТС] |
5 |
|||
|
gets and puts из библиотеки стдио ? Добавлено через 4 часа 11 минут
0 |
|
mimicria return (true); 1976 / 1111 / 221 Регистрация: 19.04.2011 Сообщений: 2,345 |
||||
|
29.10.2011, 15:44 |
6 |
|||
|
помогите найти ошибку !
int m[i]; //сам массив Так массив объявлять нельзя, читайте про динамические массивы Добавлено через 1 минуту
Выше же была рабочая программа, правда на ++. Заменить ввод/вывод и new на malloc
0 |
|
1 / 1 / 0 Регистрация: 16.10.2011 Сообщений: 45 |
|
|
29.10.2011, 15:55 [ТС] |
7 |
|
очень жаль
0 |
|
anonimious 14 / 14 / 4 Регистрация: 17.10.2011 Сообщений: 54 |
||||
|
29.10.2011, 15:56 |
8 |
|||
|
Решение
0 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Random massive = new Random(); | |
| const int massiveSize = 30; | |
| int[] maximum = new int[massiveSize]; | |
| for (int i = 0; i < maximum.Length; i++) | |
| { | |
| maximum[i] = massive.Next(0, 1000); | |
| Console.WriteLine(maximum[i]); | |
| } | |
| if (maximum[0] > maximum[1]) | |
| { | |
| Console.WriteLine($»nЛокальный максимум первый элемент {maximum[0]}»); | |
| } | |
| if (maximum[maximum.Length — 1] > maximum[maximum.Length — 2]) | |
| { | |
| Console.WriteLine($»nЛокальный максимум последний элемент {maximum[maximum.Length — 1]}»); | |
| } | |
| for (int i = 1; i < massiveSize — 1; ++i) | |
| { | |
| if (maximum[i — 1] < maximum[i] && maximum[i + 1] < maximum[i]) | |
| { | |
| Console.WriteLine(«nСписок локальных максимумовt» + maximum[i]); | |
| } | |
| } |
Нахождение локальных максимумов в одномерном массиве
Есть ли простой способ найти локальные максимумы в 1D-массиве?
Скажем, у меня есть массив:
[ 0,
1,
10, <- max
8, <- (ignore)
3,
0,
0,
4,
6, <- (ignore)
10, <- max
6, <- (ignore)
1,
0,
0,
1,
4, <- max
1,
0 ]
Я хочу, чтобы он нашел 10 и 4, но игнорировал 8 и 6, так как они находятся рядом с 10 секундами. Математически вы могли бы найти, где производная равна нулю, если бы она была функцией. Я не слишком уверен, как это сделать в Javascript.
30 июль 2014, в 22:32
Поделиться
Источник
maxes = []
for (var i = 1; i < a.length - 1; ++i) {
if (a[i-1] < a[i] && a[i] > a[i+1])
maxes.push(a[i])
}
tohava
30 июль 2014, в 21:30
Поделиться
Это вернет массив всех пиков (локальных максимумов) в данном массиве целых чисел, также заботясь о плато:
function findPeaks(arr) {
var peak;
return arr.reduce(function(peaks, val, i) {
if (arr[i+1] > arr[i]) {
peak = arr[i+1];
} else if ((arr[i+1] < arr[i]) && (typeof peak === 'number')) {
peaks.push(peak);
peak = undefined;
}
return peaks;
}, []);
}
findPeaks([1,3,2,5,3]) // -> [3, 5]
findPeaks([1,3,3,3,2]) // -> [3]
findPeaks([-1,0,0,-1,3]) // -> [0]
findPeaks([5,3,3,3,4]) // -> []
Обратите внимание, что первый и последний элементы массива не считаются пиками, потому что в контексте математической функции мы не знаем, что предшествует или следует за ними, и поэтому не может определить, являются ли они пиками или нет.
Alexander Makarenko
02 март 2017, в 21:46
Поделиться
Этот код обнаруживает локальные экстремумы (min и max, где первый вывод равен 0 и), даже если следующие элементы будут иметь равные значения (не уникальные экстремумы — т.е. 3 ‘выбирается из 1,1,1, 3,3,3,2,2,2)
var GoAsc = false; //ascending move
var GoDesc = false; //descending move
var myInputArray = [];
var myExtremalsArray = [];
var firstDiff;
for (index = 0; index < (myArray.length - 1); index++) {
//(myArray.length - 1) is because not to exceed array boundary,
//last array element does not have any follower to test it
firstDiff = ( myArray[index] - myArray[index + 1] );
if ( firstDiff > 0 ) { GoAsc = true; }
if ( firstDiff < 0 ) { GoDesc = true; }
if ( GoAsc === true && GoDesc === true ) {
myExtremalsArray.push(myArray[index]);
GoAsc = false ;
GoDesc = false;
//if firstDiff > 0 ---> max
//if firstDiff < 0 ---> min
}
}
user3473058
05 сен. 2014, в 09:32
Поделиться
Math.max выполняется для этого, но вместо массива он принимает ряд аргументов.
apply вызывает функцию с аргументами, переданными как массив.
Math.max.apply(null, array) делает трюк.
Joe Maffei
17 дек. 2017, в 18:26
Поделиться
Две ситуации: когда у вас есть пик, который является значением больше предыдущего и больше следующего, и плато, которое является значением, большим, чем предыдущее, и равно следующему (-ым), пока вы не найдете следующее другое значение, которое мне нужно меньше.
поэтому, когда вы нашли плато, временно создайте массив из этой позиции «до конца» и найдите следующее другое значение (Array.prototype. find возвращает первое значение, которое соответствует условию) и убедитесь, что оно меньше первого значения плато.
эта конкретная функция вернет индекс первого значения плато.
function pickPeaks(arr){
return arr.reduce( (res, val, i, self) => {
if(
// a peak when the value is greater than the previous and greater than the next
val > self[i - 1] && val > self[i + 1]
||
// a plateau when the value is greater than the previuos and equal to the next and from there the next different value is less
val > self[i - 1] && val === self[i + 1] && self.slice(i).find( item => item !== val ) < val
){
res.pos.push(i);
res.peaks.push(val);
}
return res;
}, { pos:[],peaks:[] } );
}
console.log(pickPeaks([3,2,3,6,4,1,2,3,2,1,2,3])) //{pos:[3,7],peaks:[6,3]}
console.log(pickPeaks([-1, 0, -1])) //{pos:[1],peaks:[0]}
console.log(pickPeaks([1, 2, NaN, 3, 1])) //{pos:[],peaks:[]}
console.log(pickPeaks([1, 2, 2, 2, 1])) //{pos: [1], peaks: [2]} (plateau!)
Julian
29 май 2017, в 20:34
Поделиться
более декларативный подход:
const values = [3, 2, 3, 6, 4, 1, 2, 3, 2, 1, 2, 3];
const findPeaks = arr => arr.filter((el, index) => {
return el > arr[index - 1] && el > arr[index + 1]
});
console.log(findPeaks(values)); // => [6, 3]
vitkon
23 дек. 2016, в 17:26
Поделиться
Как насчет простой итерации?
var indexes = [];
var values = [0,1,10,8,3,0,0,4,6,10,6,1,0,0,1,4,1,0];
for (var i=1; i<values.length-1; i++)
if (values[i] > values[i-1] && values[i] > values[i+1])
indexes.push(i);
barak manos
30 июль 2014, в 19:59
Поделиться
Ещё вопросы
- 1Как вывести тип аргумента? расширяет класс в объявлении интерфейса
- 1Как измерить время отклика на действия в приложениях Android?
- 1Общие методы приводят это к T
- 0Расширение помощника Codeigniter
- 0Программа на С ++ показывает очень разное поведение памяти на разных машинах
- 0Пример jQuery inArray в фильтрах
- 1Циклы в Python: изменить один столбец на основе значений в других столбцах
- 0Почему поле ввода текста в IE 8 всегда на 6 пикселей шире, чем в другом браузере?
- 0Как показать ошибки в окнах оповещений после нажатия кнопки отправки с помощью угловых JS?
- 0Android с PHP веб-сервисом
- 0выбор ячейки таблицы на основе ее идентификатора с помощью jquery
- 1Утверждение и документация в классе для методов, которые ожидаются в производных классах
- 0Как определить пользовательскую метрику в Apache Superset?
- 0CSS классы не работают — разные классы, одна и та же функция
- 0Как мы можем ограничить каждое конкретное значение в одном столбце в SQL [дубликата]
- 0Показать ближе всего со спец. класс
- 0Как переименовать ссылки с вопросительным знаком?
- 0Изменить базу данных при выборе входа
- 0Стильные фрагменты текста, которые не обернуты в div
- 1Обработка пользовательских сообщений об ошибках в веб-API
- 1Масштабирование вектора до нуля?
- 1заглушка метода для всех экземпляров класса
- 0Почему встроенный не работает здесь?
- 1получить уникальный идентификатор диска в java
- 0SQL подготовленный оператор не показывает вывод
- 0Как добавить текст с пробелами для метки с помощью jquery?
- 1Как я могу изменить размер иконки на tabItem?
- 1Разрешение службы ServiceStack и определение типа контента
- 0функция mouseup при нажатии за пределами div
- 0PSQL: как получить количество записей каждого значения в группе столбцов по другому столбцу
- 0Странное поведение Angular 1.3 при копировании элемента в NG-повтор
- 0SQL Получить два столбца с Да или Нет
- 1Не удалось выполнить задачу ‘: app: lintVitalRelease’ из-за `Не удалось найти multidex-instrumentation.aar`
- 0Перерыв на слово в iOS7
- 0анимация ngAnimate не отображается
- 1Создать гиперссылку для доступа к нескольким листам Excel с помощью Python
- 0Активная запись реляционной базы данных Yii Framework 2.0
- 0Если уникальный элемент нажал / Если нажал за пределами div (включая другой уникальный элемент)
- 0только atoi возвращает первую цифру параметра char * [duplicate]
- 1dataContractSerializer известных типов
- 1Адреса пользовательских значений перечисления по порядку
- 0Как удалить первый элемент из класса контейнера в программе на C ++?
- 1Ошибка JNDI Tomcat 7.0.52 при развертывании файла WAR
- 1Трудности с использованием Python-запроса (POST) + API
- 0отредактируйте htaccess, чтобы сделать его нечувствительным к регистру
- 0Угловая Http Get с параметром
- 0Angularjs: модель не доступна
- 0Как можно заполнить сгенерированный JQuery со значениями 1-52
- 1Как получить секунды с эпохи без связи со временем устройства? [Дубликат]
- 0Маршрутизация с использованием $ stateProvider в угловых js, страница не загружается при попытке маршрутизации с использованием состояний






Сообщение было отмечено Памирыч как решение