optimization - optimizing subarray max/min analysis in python -
i'm working on hackerrank problem (found here). in problem have take given array , find subarray of length n smallest max-min value. page explains little better do.
that being said, i've finished problem , have solution believe works in every case... keep on 'timing out' on select few of test cases provide. i've included code below:
def maxmin(array, original, new): minimum = -1 in range(0, original-new-1): subarray = array[i:i+(new)] if minimum == -1: minimum = max(subarray)-min(subarray) else: if (max(subarray)-min(subarray)) < minimum: minimum = max(subarray)-min(subarray) return minimum n = input() k = input() candies = [input() _ in range(0,n)] candies.sort() print maxmin(candies, n, k)
as said above, code works fine -- apparently it's not 'fast' enough. i'm still very new python (as quick review of previous questions suggest), i'm not sure how make code more 'pythonic' or faster, in general. in regard extremely appreciated.
thanks!
why doing work?
there bunch of things code doesn't need do:
- my guess @ worst thing makes bunch of copies of list. each
subarray = array[i:i+new]
creates new list, bad. note if using numpy, wouldn't happen, you'd have other problems. it's easier use elements same list,array[i]
,array[i+new-1]
. - you don't need calculate max , min. list sorted, subarray, [0] value going min, , [-1] value going max. going array, means sublist of k values, starting @ position i,
array[i]
min, ,array[i+k-1]
max. makes things far easier. - this minimal thing, can remove conditional by, instead of setting minimum -1 start, setting very, large.
sys.maxint
of course safest, though if want avoid importingsys
, number larger expect ever see difference work. if this, don't need have special case first run-through.
alternatively, can calculate values in iterator, , min them. allows compact code; example, following works:
n,k = (input(),input()) l=[input() _ in range(0,n)]; l.sort() print min(l[i+k-1]-l[i] in xrange(0,n-k+1))
Comments
Post a Comment