def maxN(n:list[int])-> int:
if len(n)==2:
if n[0] > n[1]:
return n[0]
else:
return n[1]
if len(n) ==1:
return n[0]
else:
mid = len(n)//2
first = maxN(n[0:mid])
second= maxN(n[mid:])
if first>second:
return first
else:
return second
I'm getting struggled with my emplementation, because I don't know if this is better than simply using a for or a while loop.
CodePudding user response:
At every level, every function calls two more functions until there are no more numbers. Roughly, the total number of functions calls will be 1 2 4 8 .... n. The total length of the series would be approximately logn
as the array is halved at every level.
To get the total number of function calls, we could sum the specified GP series, which would give us the total as n
.
We see that there n
number of function calls in total and every function does constant amount of work. Thus, the time complexity would be O(n)
.
The time complexity is similar to the iterative version. However, we know that recursion consumes space in the call stack. Since there could be at most logn
functions in the call stack (the depth of the recursive tree), the space complexity will be O(logn)
.
Thus, the iterative version would be a better choice as it has the same time complexity but a better, O(1)
, space complexity.
Edit: Since the list being splitted into sublists in every function, the splitting cost would add up too. To avoid that, you could pass two variables in the function to the track the list boundary.