forked from TheAlgorithms/JavaScript
- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNumberOfLocalMaximumPoints.js
More file actions
Latest commit
45 lines (40 loc) · 1.51 KB
/
Copy pathNumberOfLocalMaximumPoints.js
File metadata and controls
45 lines (40 loc) · 1.51 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
/**
* [NumberOfLocalMaximumPoints](https://www.geeksforgeeks.org/find-indices-of-all-local-maxima-and-local-minima-in-an-array/) is an algorithm to find relative bigger numbers compared to their neighbors
*
* Notes:
* - like the other similar local maxima search function find relative maxima points in array but doesn't stop at one but returns total point count
* - runs on array A of size n and returns the local maxima count using divide and conquer methodology
*
* @complexity: O(n) (on average )
* @complexity: O(n) (worst case)
* @flow
*/
// check if returned index is a local maxima
constIsMaximumPoint=(array,index)=>{
// handle array bounds
// array start
if(index===0){
returnarray[index]>array[index+1]
// array end
}elseif(index===array.length-1){
returnarray[index]>array[index-1]
// handle index inside array bounds
}else{
returnarray[index]>array[index+1]&&array[index]>array[index-1]
}
}
constCountLocalMaximumPoints=(array,startIndex,endIndex)=>{
// stop check in divide and conquer recursion
if(startIndex===endIndex){
returnIsMaximumPoint(array,startIndex) ? 1 : 0
}
// handle the two halves
constmiddleIndex=parseInt((startIndex+endIndex)/2)
return(
CountLocalMaximumPoints(array,startIndex,middleIndex)+
CountLocalMaximumPoints(array,middleIndex+1,endIndex)
)
}
constNumberOfLocalMaximumPoints=(A)=>
CountLocalMaximumPoints(A,0,A.length-1)
export{NumberOfLocalMaximumPoints}