Tut 02 - Functions and Conditionals
Thanks for my tutor Eric Han!
Last updated
Thanks for my tutor Eric Han!
Last updated
One basic idea to let the function call by itself is to extract each element one by one from the list.
However, we may notice that using this method, our time complexity will be the same as the one without using recursion. That's because in both these two methods, we are extracting one element from the list and add them to our result.
So, How can we optimize our algorithm?
Can we use the idea of "half" in this problem?
The answer is yes. We can divide our problem into smaller ones by halving the list we are about to add. More generally speaking, we recursively divide the final answer to be left half sum + right half sum.
Also, notice that for our list, its last element is , and in this flowchart, we are assuming that sum()
is left-closed and right-open. Otherwise, we should make some small changes below
Same as the Problem 3.2(a), now our task is to calculate , which can be viewed as
Using this idea, we can form our solution
Now, we should ask ourselves the same questions. Can we still optimize it? The answer is absolutely yes right. Using the similar idea we have introduced in Problem 3.2(a), we can apply "half" on this problem as well.
From this chart, we can directly see that the last condition if (x==y)
is duplicate. But let's take a step down further, our max
can only be either x
or y
, that means we only need one condition check. So, we can see that if (x < y)
is actually also duplicate.
Now, this is the succinct one.
Then, based on our flowchart, we can easily convert it to the if-else
statement
You can find the solution at .