int coin_row(int[] array, int index, int length)
{
if (index >= length) //beyond last coin
{
return 0;
}
int value = array[index];
if (index >= length - 1) //last coin
{
return value;
}
else if (index >= length - 2) //second last coin
{
return max(value, coin+row(array, index+1);
}
return max(value+coin_row(array, index+2,length), coin_row(array, index+1,length));
}
What should I do when calculating the time complexity of this recursive function?
It's O(n).
To see this: write a recurrence relation. Here is it T(n) = T(n+1) + O(1)
and T(l) = 1
. The O(1) in the first equation comes from the max() function.
Since each step requires O(1)
operations, and there are n recusive calls where n is the length. The time complexity is O(n*1) = O(n).
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.