I found this Suffix Sum challenge on CodeForces as I was practising recursion sums:
Given two numbers N and M, and an array A of N numbers. Calculate the sum of the last M numbers.
Note: solve this problem using recursion.
Input
First line contains two numbers N and M (1 ≤ M ≤ N ≤ 105).
Second line contains N numbers (−109 ≤ Ai ≤ 109).
Output
Print the sum of the last M numbers of the given array.
I tried to solve the question in Python, and this is my code:
def suffix_sum(arr, m):
if m <= 0:
return 0
else:
return arr[-1] + suffix_sum(arr[:-1], m - 1)
n, m = map(int,input().split())
arr = list(map(int,input().split()))
print(suffix_sum(arr, m))
Though I get the expected output in my compiler for my sample input, I always end up getting 'Memory limit exceeded on test 2' when I submit my code. Test case 2 is hidden, so I am not sure what the test case is, but my guess is that it is a really large array in the order of 104 or 105. When I checked the other submissions, they were all in C++.
So, does the memory limit exceeding have something to do with me using Python and PyPy, or is something wrong with my code?
The result gets accepted when I use a for loop, but as the question is for practising recursion, I am not sure where I am going wrong. It would be of great help if you could help me improve!