Example #1
0
 def findMaximums(self, nums):
     res = [0] * len(nums)        
     nums += [-1 * sys.maxint]
     stack = [-1]
     for i in xrange(len(nums)):
         while nums[i] < (nums[stack[-1]] if stack[-1] >= 0 else -1 * sys.maxint):
             res[i - stack[-2] - 2] = max(res[i - stack[-2] - 2], nums[stack[-1]])
             stack.pop()
         stack.append(i)
     for i in reversed(xrange(len(nums) - 2)):
         res[i] = max(res[i + 1], res[i])
     return res  
Example #2
0
 def findMaximums(self, nums: List[int]) -> List[int]:
     ans = [0]*len(nums)
     stack = []
     for i, x in enumerate(nums + [0]): 
         while stack and stack[-1][1] >= x: 
             _, xx = stack.pop()
             k = i-stack[-1][0]-2 if stack else i-1
             ans[k] = max(ans[k], xx)
         stack.append((i, x))
     
     for i in reversed(range(len(nums)-1)): 
         ans[i] = max(ans[i], ans[i+1])
     return ans
Example #3
0
 def findMaximums(self, nums: List[int]) -> List[int]:
     N = len(nums)
     cl = [None]*N
     cr = [None]*N
     
     stack = []
     for i in range(N):
         while stack and nums[stack[-1]]>=nums[i]:
             stack.pop()
         if not stack:
             cl[i] = i+1
         else:
             cl[i] = i-stack[-1]
         stack.append(i)
     # now cl[i]==a means that nums[i] is a minimum of the range of length a starting from i 
     # and going to the left
         
     stack = []
     for i in range(N-1,-1,-1):
         while stack and nums[stack[-1]]>=nums[i]:
             stack.pop()
         if not stack:
             cr[i] = N-i
         else:
             cr[i] = stack[-1]-i
         stack.append(i)
     # now cr[i]==b means that nums[i] is a minimum of the range of length b starting from i 
     # and going to the right
         
     
     cnt = [a+b-1 for a,b in zip(cl,cr)]
     # cnt[i]==c means that there is a subarray of length c where nums[i] is a minimum
     # and c is the maximum possible one
     
     cnti = sorted(range(N), key=cnt.__getitem__, reverse=True) # reverse argsort
     ofs = 0
     ans = [None]*N
     best = -10**10
     for L in range(N,0,-1):
         # will fill ans[L-1]
         # ans[L-1] is the max of all such nums[i] that cnt[i]>=L
         while ofs<N and cnt[cnti[ofs]]>=L:
             best = max(best,nums[cnti[ofs]])
             ofs += 1
         ans[L-1] = best
     return ans
Example #4
0
 def findMaximums(self, nums: List[int]) -> List[int]:
     stack, n = [], len(nums)
     ans = [0] * n
     for i, num in enumerate(nums):
         while stack and nums[stack[-1]] >= num:              # ensure mono-increase
             min_idx = stack.pop()                            # min_idx is the `stack_top_idx` we mentioned earlier, smallest between `left` and `right` below
             left, right = (stack[-1] + 1) if stack else 0, i # left & right end of window, left is `second_stack_top_idx + 1`, right is `i`
             window = right - left - 1                        # window_size_idx = window size - 1
             ans[window] = max(ans[window], nums[min_idx])    # update maximum
         stack.append(i)
     else:
         while stack:                                         # at the end of iteration, we want to pop out all elements in stack. Here assuming the `current_value` is super small, so that every number in the stack will be popped out
             min_idx = stack.pop()
             left, right = (stack[-1] + 1) if stack else 0, n
             window = right - left - 1    
             ans[window] = max(ans[window], nums[min_idx])
     for i in range(n-2, -1, -1):                             # update non-touched windows using result for larger windows
         ans[i] = max(ans[i], ans[i+1])
     return ans
Example #5
0
	def getExternalRPMS(self):
		import stack.roll
		import stack.gen

		# The default-all distribution includes all of the
		# installed pallets on the system and is used to generate a
		# kickstart files for the everything appliance. This gives us
		# a list of RPMs that we know we need from the source
		# os/updates CDs.

		cwd = os.getcwd()

		print 'making default-all'

		self.command('create.distribution', [ 'default-all',
			'inplace=true', 'resolve=true', 'md5=false' ])

		#
		# copy the 'everything' node and graph file into the distribution
		#
		basedir = os.path.join('default-all', self.arch, 'build')
		xml = self.command('list.node.xml', [ 'everything',
			'basedir=%s' % basedir, 'eval=n' ] )

		os.chdir(cwd)

		#
		# make sure the XML string is ASCII and not unicode, 
		# otherwise, the parser will fail
		#
		xmlinput = xml.encode('ascii', 'ignore')

		generator = stack.gen.Generator_redhat()
		generator.setArch(self.arch)
		generator.setOS('redhat')
		generator.parse(xmlinput)

		rpms = []
		for line in generator.generate('packages'):
			if len(line) and line[0] not in [ '#', '%' ]:
				rpms.append(line)

		# The default-os distribution includes just the source
		# os/update CDs (already in pallet form).
		# The default-all distribution is
		# still used for the comps file and the anaconda source 
		# code.  We need this since anaconda and comps are missing
		# from the foreign pallets (os/update CDs).

		print 'making default-os'

		self.command('create.distribution', [ 'default-os',
			'inplace=true', 'resolve=true', 'md5=false' ])

		#
		# make sure a comps.xml file is present
		#
		comps = os.path.join('default-os', self.arch, 'RedHat',
			'base', 'comps.xml')
		if not os.path.exists(comps):
			print '\n\tCould not find a comps.xml file.'
			print '\tCopy a comps.xml file into the CentOS pallet\n'
			sys.exit(-1)

		#
		# use yum to resolve dependencies
		#
		sys.path.append('/usr/lib/python2.6/site-packages')
		sys.path.append('/usr/lib64/python2.6/site-packages')
		sys.path.append('/usr/lib/python2.6/lib-dynload')
		sys.path.append('/usr/lib64/python2.6/lib-dynload')
		import yum

		#
		# need to create a repo here because the 'md5=false' flag above
		# does not call createrepo and we need it below for yum to work
		#
		os.system('/usr/share/createrepo/genpkgmetadata.py ' +
			'--groupfile RedHat/base/comps.xml ' +
			'default-os/%s' % self.arch)

		a = yum.YumBase()
		a.doConfigSetup(fn='%s' % os.path.join(cwd, 'BUILD',
			'roll-%s-%s' % (self.config.getRollName(),
			self.config.getRollVersion()), 'yum.conf'),
			init_plugins=False)
		a.conf.cache = 0
		a.doTsSetup()
		a.doRepoSetup()
		a.doRpmDBSetup()
		a.doSackSetup()
		a.doGroupSetup()

		selected = []
		for rpm in rpms + [ '@base', '@core' ]:
			if rpm[0] == '@':
				group = a.comps.return_group(
					rpm[1:].encode('utf-8'))

				for r in group.mandatory_packages.keys() + \
						group.default_packages.keys():
					if r not in selected:
						selected.append(r)
			elif rpm not in selected:
				selected.append(rpm)

		pkgs = []
		avail = a.pkgSack.returnNewestByNameArch()
		for p in avail:
			if p.name in selected:
				pkgs.append(p)

		done = 0
		while not done:
			done = 1
			results = a.findDeps(pkgs)
			for pkg in results.keys():
				for req in results[pkg].keys():
					reqlist = results[pkg][req]
					for r in reqlist:
						if r.name not in selected:
							selected.append(r.name)
							pkgs.append(r)
							done = 0

		# Now build a list of rocks (required) and non-rocks (optional)
		# rpms and return both of these list.  When the ISOs are created
		# all the required packages are first.
		
		tree = stack.file.Tree(os.path.join(os.getcwd(),
			'default-os', self.arch))

		stack = []
		nonstack = []
		for rpm in tree.getFiles(os.path.join('RedHat', 'RPMS')):
			if rpm.getBaseName() in selected:
				stack.append(rpm)
			else:
				nonstack.append(rpm)

		return (stack, nonstack)
Example #6
0
				queue.pop()
			queue.append(i)
            if i - last + 1 == length: 
				max_min = max(max_min, nums[queue[0]])
		return max_min
        
    return [helper(i + 1) for i in range(len(nums))]
It turned out that this is a tricky problem using monotonic stack, where the poped up value might be the result for the query with length of stack[-1] ... current i. Why?
We maintain the increasing monotonic stack, keeping popup the stack[-1] if nums[stack[-1]] >= num, and we havenums[stack[-2]] < nums[stack[-1]] >= num. So the nums[stack[-1]] is the minimum value of subarray with range of [stack[-2] +1: i - 1]. Because if there is any larger value x in the range, the stack[-1] should have been popped up when seeing x. So we can update the query[range] with nums[stack[-1]].
Finally, there is possible to be no result yet for some queris. With observation, the maximum value would be the result of query[0], and the minimum value would be the result of query[-1], so the query array is actually deceasing. Then we can fill up the empty slot in query array by propagating the previous value.

def findMaximums(self, nums: List[int]) -> List[int]:
	stack = []
    nums = [-1] + nums + [0]
    n = len(nums)
    res = [0] * (n - 2)
    for i, num in enumerate(nums):
		while stack and nums[stack[-1]] >= num:
			j = stack.pop()
            k = i - 1 - (stack[-1] + 1)
			res[k] = max(res[k], nums[j])
		stack.append(i)      

	for i in range(n - 3, 0, -1):
		res[i - 1] = max(res[i], res[i - 1])
	return res
        
        
        
      
def dec_binary(num):
    if num > 1:
        dec_binary(num//2)
        stack.append(str(num % 2))
Example #8
0
    def getExternalRPMS(self):
        import stack.roll
        import stack.gen

        # The default-all distribution includes all of the
        # installed pallets on the system and is used to generate a
        # kickstart files for the everything appliance. This gives us
        # a list of RPMs that we know we need from the source
        # os/updates CDs.

        cwd = os.getcwd()

        print 'making default-all'

        self.command(
            'create.distribution',
            ['default-all', 'inplace=true', 'resolve=true', 'md5=false'])

        #
        # copy the 'everything' node and graph file into the distribution
        #
        basedir = os.path.join('default-all', self.arch, 'build')
        xml = self.command(
            'list.node.xml',
            ['everything', 'basedir=%s' % basedir, 'eval=n'])

        os.chdir(cwd)

        #
        # make sure the XML string is ASCII and not unicode,
        # otherwise, the parser will fail
        #
        xmlinput = xml.encode('ascii', 'ignore')

        generator = stack.gen.Generator_redhat()
        generator.setArch(self.arch)
        generator.setOS('redhat')
        generator.parse(xmlinput)

        rpms = []
        for line in generator.generate('packages'):
            if len(line) and line[0] not in ['#', '%']:
                rpms.append(line)

        # The default-os distribution includes just the source
        # os/update CDs (already in pallet form).
        # The default-all distribution is
        # still used for the comps file and the anaconda source
        # code.  We need this since anaconda and comps are missing
        # from the foreign pallets (os/update CDs).

        print 'making default-os'

        self.command(
            'create.distribution',
            ['default-os', 'inplace=true', 'resolve=true', 'md5=false'])

        #
        # make sure a comps.xml file is present
        #
        comps = os.path.join('default-os', self.arch, 'RedHat', 'base',
                             'comps.xml')
        if not os.path.exists(comps):
            print '\n\tCould not find a comps.xml file.'
            print '\tCopy a comps.xml file into the CentOS pallet\n'
            sys.exit(-1)

        #
        # use yum to resolve dependencies
        #
        if stack.release == '7.x':
            pythonver = '2.7'
        else:
            pythonver = '2.6'

        sys.path.append('/usr/lib/python%s/site-packages' % pythonver)
        sys.path.append('/usr/lib64/python%s/site-packages' % pythonver)
        sys.path.append('/usr/lib/python%s/lib-dynload' % pythonver)
        sys.path.append('/usr/lib64/python%s/lib-dynload' % pythonver)

        import yum

        #
        # need to create a repo here because the 'md5=false' flag above
        # does not call createrepo and we need it below for yum to work
        #
        os.system('/usr/share/createrepo/genpkgmetadata.py ' +
                  '--groupfile RedHat/base/comps.xml ' +
                  'default-os/%s' % self.arch)

        a = yum.YumBase()
        a.doConfigSetup(fn='%s' % os.path.join(
            cwd, 'BUILD', 'roll-%s-%s' %
            (self.config.getRollName(), self.config.getRollVersion()),
            'yum.conf'),
                        init_plugins=False)
        a.conf.cache = 0
        a.doTsSetup()
        a.doRepoSetup()
        a.doRpmDBSetup()
        a.doSackSetup()
        a.doGroupSetup()

        selected = []
        for rpm in rpms + ['@base', '@core']:
            if rpm[0] == '@':
                group = a.comps.return_group(rpm[1:].encode('utf-8'))

                for r in group.mandatory_packages.keys() + \
                  group.default_packages.keys():
                    if r not in selected:
                        selected.append(r)
            elif rpm not in selected:
                selected.append(rpm)

        pkgs = []
        avail = a.pkgSack.returnNewestByNameArch()
        for p in avail:
            if p.name in selected:
                pkgs.append(p)

        done = 0
        while not done:
            done = 1
            results = a.findDeps(pkgs)
            for pkg in results.keys():
                for req in results[pkg].keys():
                    reqlist = results[pkg][req]
                    for r in reqlist:
                        if r.name not in selected:
                            selected.append(r.name)
                            pkgs.append(r)
                            done = 0

        # Now build a list of rocks (required) and non-rocks (optional)
        # rpms and return both of these list.  When the ISOs are created
        # all the required packages are first.

        tree = stack.file.Tree(
            os.path.join(os.getcwd(), 'default-os', self.arch))

        stack = []
        nonstack = []
        for rpm in tree.getFiles(os.path.join('RedHat', 'RPMS')):
            if rpm.getBaseName() in selected:
                stack.append(rpm)
            else:
                nonstack.append(rpm)

        return (stack, nonstack)