This challenge is from Talent Buddy:
Tweets per second
Japan Castle in the Sky airing broke a Twitter record on August 3, 2013. At one point during the classic anime movie showing, people submitted 143,199 tweets per second. This particular spike was about 25 times greater than Twitter’s steady state.
Given an array of integers representing the number of tweets recorded every second and an integer value
K
, your task is to write a function that prints to the standard output (stdout) the highest number of tweets recorded between each second in the array and the pastK
seconds before itNote that your function will receive the following arguments:
tps
, which is an array of integers representing the number of tweets recorded every second, andk
, which is the integer number mentioned above.Data constraints: the length of the array above will not exceed 500,000 numbers
Efficiency constraints: your function is expected to print the requested result and return in less than 2 seconds
Example Input
tps: 6, 9, 4, 7, 4, 1
k: 3
Output
6 9 9 9 7 7
Please Note: The above program should run in below 2 seconds
My Program
start=1
for i,j in enumerate(tps):
if start<=k:
print max(tps[:start])
start+=1
else:
print max(tps[i-(start)+2:i+1])
This function takes more than 2 seconds for the test case.
How can we do same thing less in than 2 seconds? How can this be optimized to make it faster?
N * k
, whereN
is the number of items in the list. There are linear time algorithms for this, you may want to take a look at this. There is a Cython version in pandas you can check here. \$\endgroup\$