Issue
So I've been going through the tests on codility and got bit stuck with the "Max Counters" one (link https://codility.com/demo/take-sample-test/max_counters). My first, and obvious solution was the following one:
def solution(N, A):
counters = N * [0];
for a in A:
if 1 <= a <= N:
counters[a - 1] += 1;
elif a == N + 1:
counters = N * [max(counters)];
return counters
which works just fine, but takes too much time, due to the fact that each call to max counters fills an entire array.
So I came up with the following solution which seems to work ok for small inputs, but randomly provides incorrect results for medium and large ones.
def solution(N, A):
counters = N * [0];
current_max = 0;
last_update = 0;
for a in A:
if 1 <= a <= N:
counters[a - 1] += 1;
if counters[a - 1] < last_update:
counters[a - 1] = last_update + 1;
if counters[a - 1] > current_max:
current_max = counters[a - 1];
elif a == N + 1:
last_update = current_max;
for i in xrange(len(counters)):
if counters[i] < last_update:
counters[i] = last_update;
return counters
I can't seem to figure out what's wrong with it.
Edit: Result - http://codility.com/demo/results/demoQA7BVQ-NQT/
Solution
One problem is here:
counters[a - 1] += 1
if counters[a - 1] < last_update:
counters[a - 1] = last_update + 1
what if counters[a - 1]
was last_update - 1
?
Answered By - jonrsharpe
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.