Program to check maximum sum of all stacks after popping some elements from them in Python


Suppose we have a list of stacks, we can take any stack or stacks and pop any number of elements from it. We have to find the maximum sum that can be achieved such that all stacks have the same sum value.

So, if the input is like stacks = [[3, 4, 5, 6], [5, 6, 1, 4, 4], [10, 2, 2, 2] ], then the output will be 12, as we can take operations like −

  • Pop [6] from the first stack we get [3, 4, 5] the sum is 12.

  • Pop [4,4] from the second stack we get [5, 6, 1] the sum is 12.

  • Pop [2,2] from the third stack we get [10, 2] the sum is 12.

To solve this, we will follow these steps −

  • sums := an empty map

  • for each stk in stacks, do

    • s := 0

    • for each n in stk, do

      • s := s + n

      • sums[s] := sums[s] + 1

  • ans := 0

  • for each key value pairs (s, f) of sums, do

    • if f >= stack count and s > ans, then

      • ans := s

  • return ans

Let us see the following implementation to get better understanding −

Example

 Live Demo

from collections import defaultdict
class Solution:
   def solve(self, stacks):
      sums = defaultdict(int)
      for stk in stacks:
         s = 0
         for n in stk:
            s += n
            sums[s] += 1
         ans = 0
         for s, f in sums.items():
            if f >= len(stacks) and s > ans:
               ans = s
         return ans
ob1 = Solution()
stacks = [
   [3, 4, 5, 6],
   [5, 6, 1, 4, 4],
   [10, 2, 2, 2]
]
print(ob1.solve(stacks))

Input

stacks = [ [3, 4, 5, 6], [5, 6, 1, 4, 4], [10, 2, 2, 2] ]

Output

12

Updated on: 21-Oct-2020

202 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements