算法来平衡阵列中的一个子区间元素的数量

算法来平衡阵列中的一个子区间元素的数量

本文介绍了算法来平衡阵列中的一个子区间元素的数量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可以说,你有4个不同类型的元素的数组。

  1 1 2 3 1 2 2 3 3 4 4 1。
 

我想找到最长的子区间,其导致相同数量的每个元素和元素的最大数量。

在这种情况下,这将是

因为这将导致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

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

这篇关于算法来平衡阵列中的一个子区间元素的数量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 10:52