Live Note

Remain optimistic

6.006 - 1

find the peak.

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
46
47
48
49
50
51
52
/**
* Find the peek 1D
* @param {Array<number>} arr arr
* @param {number} i the index to start
* @param {number} j the index to end
* @returns {number} the peak
*/
let findThePeak = (arr, i, j) => {
let current = parseInt((i + j) / 2)

if (arr[current] < arr[current + 1]) return findThePeak(arr, current, j)
else if (arr[current] < arr[current - 1]) return findThePeak(arr, i, current)
else return arr[current]
}

/**
* Find the peak 2D
* @param {Array<Array<number>>} arr the Number[][] array
* @param {number} start start row
* @param {number} end end row
* @returns {number} the peak of the array
*/
let findThePeak2 = (arr, start, end) => {
let current = parseInt((start + end) / 2)
let rowMax = findThePeak(arr[current], 0, arr[current].length)

// get the index of column
// let i = arr[current].indexOf(rowMax)
let i = arr[current]
.map((i, index) => i === rowMax && index)
.filter((i) => i !== false)[0]

if (current - 1 >= 0 && arr[current][i] < arr[current - 1][i]) {
// check the left part
return findThePeak2(arr, start, current)
} else if (current < end - 1 && arr[current][i] < arr[current + 1][i]) {
// check the right part
return findThePeak2(arr, current, end)
} else {
return rowMax
}
}

let arr = [5, 4, 3, 2, 4, 5, 6]
let arr2 = [
[6, 3, 8],
[3, 2, 1],
[4, 6, 1],
]

console.log(findThePeak(arr, 0, arr.length))
console.log(findThePeak2(arr2, 0, arr2.length))

result:
6 8