-
Notifications
You must be signed in to change notification settings - Fork 0
/
monotonic-array.go
81 lines (66 loc) · 1.55 KB
/
monotonic-array.go
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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
package main
import (
"fmt"
"reflect"
)
/*
Write a function that takes in an array of integers and returns a boolean
representing whether the array is monotonic.
An array is said to be monotonic if its elements, from left to right,
are entirely non-increasing or entirely non-decreasing
example:
input: [-1, -5, -10, -1100, -1101, -1102, -9001]
output: true
input: [1, 2, 0]
output: false
*/
// Time: O(n) | Space: O(1)
func isMonotonic(array []int) bool {
if len(array) <= 2 {
return true
}
trendFound := false
isIncreasing := false
i := 1
for i < len(array) {
if array[i-1] == array[i] {
i++
continue
} else if !trendFound {
isIncreasing = array[i-1] < array[i]
trendFound = true
}
if array[i-1] < array[i] != isIncreasing {
return false
}
i++
}
return true
}
func main() {
want := true
got := isMonotonic([]int{-1, -5, -10, -1100, -1101, -1102, -9001})
if !reflect.DeepEqual(want, got) {
fmt.Printf("want: %v, got: %v", want, got)
}
want = true
got = isMonotonic([]int{1})
if !reflect.DeepEqual(want, got) {
fmt.Printf("want: %v, got: %v", want, got)
}
want = true
got = isMonotonic([]int{-1, -1, -1, -1, -1, -1, -1, -1})
if !reflect.DeepEqual(want, got) {
fmt.Printf("want: %v, got: %v", want, got)
}
want = false
got = isMonotonic([]int{1, 2, 0})
if !reflect.DeepEqual(want, got) {
fmt.Printf("want: %v, got: %v", want, got)
}
want = false
got = isMonotonic([]int{1, 1, 2, 3, 4, 5, 5, 5, 6, 7, 8, 7, 9, 10, 11})
if !reflect.DeepEqual(want, got) {
fmt.Printf("want: %v, got: %v", want, got)
}
}