2
$\begingroup$

One question from the Grokking Algorithms book:

Implement a max([]int) function, returning the biggest element in the array.

Here's my solution in Golang (adapted from the Python solution in the book):

func maxNumber(arr []int) (r int) {
 // base case
 if len(arr) == 2 {
 if arr[0] > arr[1] {
 return arr[0]
 } else {
 return arr[1]
 }
 }
 // recursive case
 subMax := maxNumber(arr[1:])
 if arr[0] > subMax {
 fmt.Println("arr[0] > subMax")
 return arr[0]
 } else {
 fmt.Println("arr[0] < subMax")
 return subMax
 }
}

It works, but I can wrap my head around it. How is the third block called if every time maxNumber(arr[1:]) is called it executes the function again, passing the array with one last element? If so, at some point in time it will hit the first block (base case) and return or the first element or the second.

I know the function works, but I'm missing the how.

Could someone help me around, explain like I'm 5 styles haha

Thanks!

asked Oct 9, 2019 at 13:44
$\endgroup$
2
  • $\begingroup$ arr[1:] is the list arr without its first element. So the array argument becomes shorter at each level of recursion, until finally it has only two elements, which is the base case. Does that help ? $\endgroup$ Commented Oct 9, 2019 at 14:03
  • $\begingroup$ By the way it doesn't work for an array of length 1, and making it work would make the algorithm simpler $\endgroup$ Commented Oct 9, 2019 at 14:07

1 Answer 1

1
$\begingroup$

The base case works because, if the array contains only 2 elements, it compares them and return the biggest. Starting from this assumption, the recursive call to the function maxNumber compare the maxnumber of the precedent call to the next element in the array. when the list has been read all the way to the end, the algorithm will return the max number of the whole list.

answered Oct 9, 2019 at 14:17
$\endgroup$
1
  • $\begingroup$ Thanks it helped a lot! Also I used Python Visualizer (and Python code), which helped me even more ✨ tinyurl.com/y6lg85qj $\endgroup$ Commented Oct 9, 2019 at 18:21

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.