Recently I have encountered what seems to be a quite interesting game that suggest implementing both two-pointers and prefix-sum techniques on a large dataset. Here is the task itself:
Imagine there is an array v of length k where k (k<=10**5) represents the amount of entries consisting of two numbers: A (so-called pile) and N(the amount), for example:
k = 3
v = [[2, 2], [3, 2], [2, 1]]
A (v[i][0]
) is the value and N (v[i][1]
) is the number of times this value is given. In other words, N is the frequency of A.
Now, what we have to do is to choose the minimum A, starting from both ends of the list, subtract it from the current positions and add it to the following ones. Then we continue doing so before there are only two or one etries left in the middle. In other words, each step we choose the smallest pile and substract it from both ends until one or two piles left.
The answer should include two lines: the first contains either '1' or '2' depending on how much piles are left, and the second is the result itself.
To simplify, we can represent piles as a plain list that looks like this:
v = [2, 2, 3, 3, 2]
We choose the minimum from the left and the right ends (2), substract it and add to the next values:
v = [0, 4, 3, 5, 0]
The minimum of 4 and 5 is 4, so we substract 4 and get two piles.
v = [0, 0, 11, 1, 0]
And the output is:
2
11 1
My code is:
k = int(input())
a = []
for _ in range(k):
A, N = map(int, input().split())
x = [A] * N
a += x
l = 0
r = len(a)-1
while r - l > 1:
s = min(a[l], a[r])
a[l] -= s
a[r] -= s
a[l+1] += s
a[r-1] += s
if a[l] == 0:
l += 1
if a[r] == 0:
r -= 1
if a[r] == 0 or a[r]==a[l]:
print(1)
print(a[l])
else:
print(2)
print(a[l], a[r])
This solution fails the time limit (2sec) with k = 10**5 because it requires converting an array into a plain list and also barely employs prefix-sum. I know for sure that there is a much faster solution with prefix-sum, additional variables and storing an array as given. Would be grateful for any advice on how I can speed up this code.
To prevent any language-related comments: the game is given for any programming language so the time limit is not specifically python's issue.