Equal Stacks

  • + 0 comments

    I use a map for elements index and sums and increment index on the list with the lowest sum each loop

    time O(n) space O(1)

    def equalStacks(h1, h2, h3):
        # Write your code here
        max_val = 0
        index = {1: -1, 2: -1, 3: -1}
        sums = {1: 0, 2: 0, 3: 0}
        h1.reverse()
        h2.reverse()
        h3.reverse()
        list_map = {1: h1, 2: h2, 3: h3}
        while True:
            if not index:
                break
            next_index_sum = min([v for k, v in sums.items() if k in index])
            list_key = {v: k for k, v in sums.items() if k in index}[next_index_sum]
            next_block_index = index[list_key] +1
            if next_block_index <= list_map[list_key].__len__() -1:
                sums[list_key] += list_map[list_key][next_block_index]
                index[list_key] +=1
            else:
                del index[list_key]
            if len(set(sums.values())) == 1:
                max_val = max(max_val, sums[1])
        return max_val