diff --git a/Data-Structures/Array/LocalMaximomPoint.js b/Data-Structures/Array/LocalMaximomPoint.js new file mode 100644 index 000000000..c19985614 --- /dev/null +++ b/Data-Structures/Array/LocalMaximomPoint.js @@ -0,0 +1,30 @@ +/** + * [LocalMaxima](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: + * - works by using divide and conquer + * - the function gets the array A with n Real numbersand returns the local max point index (if more than one exists return the first one) + * + * @complexity: O(log(n)) (on average ) + * @complexity: O(log(n)) (worst case) + * @flow + */ +const findMaxPointIndex = (array, rangeStartIndex, rangeEndIndex, originalLength) => { + // find index range middle point + const middleIndex = rangeStartIndex + parseInt((rangeEndIndex - rangeStartIndex) / 2) + + // handle array bounds + if ((middleIndex === 0 || array[middleIndex - 1] <= array[middleIndex]) && + (middleIndex === originalLength - 1 || array[middleIndex + 1] <= array[middleIndex])) { + return middleIndex + } else if (middleIndex > 0 && array[middleIndex - 1] > array[middleIndex]) { + return findMaxPointIndex(array, rangeStartIndex, (middleIndex - 1), originalLength) + } else { + // regular local max + return findMaxPointIndex(array, (middleIndex + 1), rangeEndIndex, originalLength) + } +} + +const LocalMaximomPoint = (A) => findMaxPointIndex(A, 0, A.length - 1, A.length) + +export { LocalMaximomPoint } diff --git a/Data-Structures/Array/test/LocalMaximomPoint.test.js b/Data-Structures/Array/test/LocalMaximomPoint.test.js new file mode 100644 index 000000000..e2f188310 --- /dev/null +++ b/Data-Structures/Array/test/LocalMaximomPoint.test.js @@ -0,0 +1,29 @@ +import { LocalMaximomPoint } from '../LocalMaximomPoint' + +describe('LocalMaximomPoint tests', () => { + it('test boundry maximom points - last element', () => { + const Array = [1, 2, 3, 4, 5, 6, 12] + expect(LocalMaximomPoint(Array)).toEqual(6) + }) + + it('test boundry maximom points - first element', () => { + const Array2 = [13, 6, 5, 4, 3, 2, 1] + expect(LocalMaximomPoint(Array2)).toEqual(0) + }) + + it('test boundry maximom points - should find first maximom point from the top', () => { + // Test a mix of number types (i.e., positive/negative, numbers with decimals, fractions) + const Array = [13, 2, 3, 4, 5, 6, 12] + expect(LocalMaximomPoint(Array)).toEqual(6) + }) + + it('test inner points - second element', () => { + const Array2 = [13, 16, 5, 4, 3, 2, 1] + expect(LocalMaximomPoint(Array2)).toEqual(1) + }) + + it('test inner points - element some where in the middle', () => { + const Array2 = [13, 16, 5, 41, 3, 2, 1] + expect(LocalMaximomPoint(Array2)).toEqual(3) + }) +})