平衡数组子区间中元素数量的算法?

时间:2014-04-06 23:05:10

标签: arrays algorithm dynamic-programming

假设您有一个包含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个和3个。

我相信这是某种修改过的动态编程,或需要前缀总和的东西,但我不太确定。有人能告诉我如何开始吗?

1 个答案:

答案 0 :(得分:-1)

#!/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