Algorithm that balances the number of elements in a subinterval of an array? -
lets have array 4 different types of elements.
1 1 2 3 1 2 2 3 3 4 4 1.
i want find longest subinterval results in equal number of each elements , largest total number of elements.
in case,
1 1 2 3 1 2 2 3 3
because results in 3 twos, 3 threes, , 3 ones.
i believe sort of modified dynamic programming, or requires prefix sums not sure. can give me insight on how start?
#!/usr/bin/env python #the demo data set = [1,1,2,3,1,2,2,3,3,4,4,1] #function map counts of values in set def map(x): ret = {} v in x: if v not in ret.keys(): ret.update({v:0}) ret[v] += 1 return ret #function check if counts in map same def checkmap(x): val = none k,v in x.items(): if val != none , v != val: return false else: val=v return true #determine initial counts counts = map(set) #now step end index start ix in range(len(set) - 1, 0, -1): val = set[ix] counts[val] += -1 if counts[val] == 0: del counts[val] if checkmap(counts): print "condition reached, largest subset is:",set[0:ix] break
Comments
Post a Comment