- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

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 −

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))

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

12

- Related Questions & Answers
- Program to find maximum sum of popped k elements from a list of stacks in Python
- Program to find mean of array after removing some elements in Python
- Popping elements from a Stack in Javascript
- Find maximum sum possible equal sum of three stacks in C++
- Program to find sum of all elements of a tree in Python
- Find maximum array sum after making all elements same with repeated subtraction in C++
- Maximum sum of increasing order elements from n arrays in C++ program
- Program to find sum of odd elements from list in Python
- Program to find out the sum of the maximum subarray after a operation in Python
- Maximum Subarray Sum after inverting at most two elements in C++
- Program to find maximum sum by flipping each row elements in Python
- Program to check some elements in matrix forms a cycle or not in python
- Maximum sum of increasing order elements from n arrays in C++
- Program to find sum of contiguous sublist with maximum sum in Python
- Python Program to Implement Queues using Stacks

Advertisements