Middle
Is a slice monotonic? A monotonic function is a single-variable function defined on some subset of real numbers, which is either non-decreasing everywhere (on its domain) or non-increasing everywhere. {1,7} - true {1,1} - true {3,3,1} - true {9,5,1} - true {23,5,23} - false
sobes.tech AI
Answer from AI
To determine if a slice is monotonic, you need to check whether it is either non-decreasing (each next element is not less than the previous one) or non-increasing (each next element is not greater than the previous one).
Example of a function in Go that checks the monotonicity of a slice of integers:
func isMonotonic(nums []int) bool {
if len(nums) <= 1 {
return true
}
increasing := true
decreasing := true
for i := 1; i < len(nums); i++ {
if nums[i] > nums[i-1] {
decreasing = false
}
if nums[i] < nums[i-1] {
increasing = false
}
}
return increasing || decreasing
}
Example usage:
fmt.Println(isMonotonic([]int{1,7})) // true
fmt.Println(isMonotonic([]int{1,1})) // true
fmt.Println(isMonotonic([]int{3,3,1})) // true
fmt.Println(isMonotonic([]int{9,5,1})) // true
fmt.Println(isMonotonic([]int{23,5,23})) // false