Skip to main content
Stack Overflow
  1. About
  2. For Teams

You are not logged in. Your edit will be placed in a queue until it is peer reviewed.

We welcome edits that make the post easier to understand and more valuable for readers. Because community members review edits, please try to make the post substantially better than how you found it, for example, by fixing grammar or adding additional resources and hyperlinks.

Required fields*

Suffix sum using recursion: Memory limit exceeded error in Python

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!

Answer*

Draft saved
Draft discarded
Cancel
0

lang-py

AltStyle によって変換されたページ (->オリジナル) /