可以说,你有4个不同类型的元素的数组。
1 1 2 3 1 2 2 3 3 4 4 1。
我想找到最长的子区间,其导致相同数量的每个元素和元素的最大数量。
在这种情况下,这将是
1 1 2 3 1 2 2 3 3
因为这将导致3三三两两,3个三分球,和3的。
我相信这是某种形式的修改动态规划,或什么的,需要preFIX款项,但我也不太清楚。能有人给我如何开始的见解?
解决方案 #!的/ usr /斌/包膜蟒蛇
#系统演示数据
SET = [1,1,2,3,1,2,2,3,3,4,4,1]
#Function映射的值的计数在该组
高清图(X):
RET = {}
对于V IN X:
如果v不ret.keys():
ret.update({ν:0})
保留[V] + = 1
返回RET
#Function检查地图中所有数都是一样的
高清checkMap(X):
VAL =无
为K,V在x.items():
如果val =无和v = VAL!!
返回False
其他:
VAL = V
返回True
#Determine最初的数
数=地图(SET)
#Now步骤从最终指数回启动
为九在范围(LEN(SET) - 1,0,-1):
VAL = SET [九]
计数[VAL] + = -1
如果罪名[VAL] == 0:
德尔计数[VAL]
如果checkMap(计数):
打印条件达到,最大子集,将[0:九]
打破
Lets say you have an array with 4 different types of elements.
1 1 2 3 1 2 2 3 3 4 4 1.
I want to find the longest subinterval that results in an equal number of each elements and the largest total number of elements.
In this case, it would be
1 1 2 3 1 2 2 3 3
because this results in 3 twos, 3 threes, and 3 ones.
I believe this is some sort of modified dynamic programming, or something that requires prefix sums but I am not too sure. Can someone give me insight on how to start?
解决方案#!/usr/bin/env python
#The demo data
SET = [1,1,2,3,1,2,2,3,3,4,4,1]
#Function to map the counts of the values in the set
def map(x):
ret = {}
for v in x:
if v not in ret.keys():
ret.update({v:0})
ret[v] += 1
return ret
#Function to check if all counts in the map are the same
def checkMap(x):
val = None
for k,v in x.items():
if val != None and v != val:
return False
else:
val=v
return True
#Determine the initial counts
counts = map(SET)
#Now step back from end index to start
for 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
上一篇:为O(n ^ 2)对为O(n(LOGN)^ 2)LOGN
下一篇:树子树子树