Skip to content

Commit 1f5d2cc

Browse files
committed
Add valid-mountain-array
1 parent 5279393 commit 1f5d2cc

File tree

2 files changed

+52
-1
lines changed

2 files changed

+52
-1
lines changed

Easy/valid-mountain-array.md

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
Code
2+
====
3+
4+
```go
5+
func validMountainArray(arr []int) bool {
6+
if len(arr) < 3 {
7+
return false
8+
}
9+
10+
n := len(arr)
11+
12+
i := 0
13+
for i = 0; i < n-1; i++ {
14+
if arr[i] >= arr[i+1] {
15+
break
16+
}
17+
}
18+
19+
if i == 0 {
20+
return false
21+
}
22+
23+
j := i
24+
for j = i + 1; j < n; j++ {
25+
if arr[j] >= arr[j-1] {
26+
return false
27+
}
28+
}
29+
30+
if j == i+1 {
31+
return false
32+
}
33+
34+
return true
35+
}
36+
```
37+
38+
Solution in mind
39+
================
40+
41+
- Solution is a simple one pass traversal of the array.
42+
43+
- As we climb p the array we ensure that `arr[i+1] >= arr[i]`. When this is violated, we reach a peak.
44+
45+
- We must ensure the peak is not at the very beginning (`i == 0`), if it was, we never climbed up the mountain.
46+
47+
- After reaching peak, we begin to climb down, while ensuring the condition `arr[i] < arr[i-1]`, if not, we either have a rise or flat zone in the mountain.
48+
49+
- After descending from the peak, we ensure we have actually moved downwards and not stayed at the peak (`j == i+1`). This acts as a check to ensure the peak is not at the very end of the array too.

README.md

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ My collection of leet code problems solved in GoLang!
55

66
| [Easy](#easy) | [Medium](#medium) | [Hard](#hard) |
77
|---------------|-------------------|---------------|
8-
| 32 | 48 | 10 |
8+
| 33 | 48 | 10 |
99

1010
Problems finished
1111
=================
@@ -77,6 +77,8 @@ Easy
7777

7878
- [best-time-to-buy-and-sell-stock](Easy/best-time-to-buy-and-sell-stock.md)
7979

80+
- [valid-mountain-array](Easy/valid-mountain-array.md)
81+
8082
Medium
8183
------
8284

0 commit comments

Comments
 (0)