Skip to content

Commit 4a25c6a

Browse files
committed
Add 852. Peak Index in a Mountain Array
1 parent 7caa116 commit 4a25c6a

File tree

2 files changed

+49
-0
lines changed

2 files changed

+49
-0
lines changed
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
package sierikov.leetcode.tasks.medium
2+
3+
// leeetcode: https://leetcode.com/problems/peak-index-in-a-mountain-array/
4+
object PeakIndexInMountainArray {
5+
def peakIndexInMountainArray(arr: Array[Int]): Int = {
6+
// borders in which we are searching
7+
var start = 0;
8+
var end = arr.length - 1;
9+
10+
// here we can check if array size is minimum 3 elements
11+
// in this task it is guaranted by constrains
12+
// in the case if arr.length = 1, middle will be 0,
13+
// and middle + 1 will fail
14+
15+
// binary search moves start and end to each other
16+
// and cuts the range of the search in each itteration by 2
17+
while (start < end) {
18+
val middle = (start + end) / 2
19+
val pointA = arr(middle)
20+
val pointB = arr(middle + 1)
21+
22+
println(s"start is $start and end is $end in ${arr.mkString(",")}")
23+
24+
if (pointA < pointB) // increasing part
25+
start = middle + 1 // continue to search "right" part
26+
else
27+
end = middle // continue to search "left" part
28+
}
29+
30+
// here we must have A(start) > A(end)
31+
// this means, that we have found beginning of decreasing trend
32+
start
33+
}
34+
}
Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
package sierikov.leetcode.tasks.medium
2+
3+
import org.scalatest.flatspec.AnyFlatSpec
4+
import org.scalatest.matchers.should.Matchers
5+
6+
class PeakIndexInMountainArrayTest extends AnyFlatSpec with Matchers {
7+
import PeakIndexInMountainArray._
8+
9+
it should "pass example test" in {
10+
peakIndexInMountainArray(Array(0, 1, 0)) shouldBe 1
11+
peakIndexInMountainArray(Array(0, 2, 1, 0)) shouldBe 1
12+
peakIndexInMountainArray(Array(0, 10, 5, 2)) shouldBe 1
13+
}
14+
15+
}

0 commit comments

Comments
 (0)