According to the task description, the output should be a new array with all elements of array days that are larger than their previous and next elements (in increments of 1). For example, we have as input
[ ]int{3, 2, 4, 3, 7, 9}
and the output should be:
[ ]int{3, 4, 9}
At first I tried to write the next condition:
if days[i] > days[i-1] && days[i] > days[i+1] {
arr = append(arr, days[i])
}
but an error occured: index out of range [-1]
Then I changed the condition and added a special condition for the last element:
package main
import (
"fmt"
)
func chaos(days []int) []int {
var arr []int
for i := 0; i < len(days)-1; i++ {
if days[i] > days[i+1] {
arr = append(arr, days[i])
}
if days[len(days)-1] > days[len(days)-2] {
arr = append(arr, days[len(days)-1])
}
}
return arr
}
func main() {
fmt.Println(chaos([]int{3, 2, 4, 3, 7, 9}))
}
But the output is [3 9 9 4 9 9 9]
How to correctly specify the condition for the last element and why the result in my case is incorrect?