Search⌘ K

Solution Review: Maximum, Minimum Array

Understand two methods to solve array maximum and minimum problems in Go. Learn how to manipulate arrays by alternating elements from copies or reversing segments, along with analyzing their time and space complexity to improve your problem-solving skills in Go.

First solution

First, we make a copy of the input array in an auxiliary array. Then we traverse the auxiliary array from the beginning to the end and alternately insert these values into the input array. For example, we insert the last element at arr[0], then insert the first element at arr[1], and so on.

Solution code

Go (1.6.2)
package main
import ("fmt")
func MaxMinArr(arr []int, size int) {
aux := make([]int, size)
copy(aux, arr)
start := 0
stop := size - 1
for i := 0; i < size; i++ {
if i%2 == 0 {
arr[i] = aux[stop]
stop -= 1
} else {
arr[i] = aux[start]
start += 1
}
}
}
/* Testing code */
func main() {
arr := []int{1, 2, 3, 4, 5, 6, 7}
size := len(arr)
MaxMinArr(arr, size)
fmt.Println(arr)
}

Complexity analysis

The time and space complexity of this program is O(n)O(n) ...