Program to find maximum sum of popped k elements from a list of stacks in Python

This problem involves finding the maximum sum by popping exactly k elements from a list of stacks. We can only pop elements from the top of each stack, making this a dynamic programming problem where we explore different combinations of popping elements.

The key insight is that for each stack, we can choose to pop 0, 1, 2, ... up to all elements from that stack, and recursively solve for the remaining stacks with the remaining number of elements to pop.

Algorithm Approach

We use a recursive function that takes the current stack index and the number of elements already popped. For each stack, we try popping different numbers of elements and choose the combination that gives the maximum sum.

Example

Let's implement the solution step by step ?

import math

class Solution:
    def solve(self, stacks, k):
        def rec(i, n):
            # Base case: if we've popped exactly k elements
            if n == k:
                return 0
            # If we've popped more than k elements, invalid
            if n > k:
                return -math.inf
            # If we've processed all stacks but haven't popped k elements
            if i == len(stacks):
                return -math.inf
            
            # Special case: last stack
            if i == len(stacks) - 1:
                needed = k - n
                if needed > len(stacks[i]):
                    return -math.inf
                else:
                    # Sum of last 'needed' elements from the stack
                    return sum(stacks[i][-needed:])
            
            res, su = -math.inf, 0
            
            # Try popping different numbers of elements from current stack
            for sti in range(len(stacks[i]) - 1, -1, -1):
                su += stacks[i][sti]
                localres = su + rec(i + 1, n + len(stacks[i]) - sti)
                res = max(res, localres)
            
            # Also try not popping any element from current stack
            return max(res, rec(i + 1, n))
    
        return rec(0, 0)

# Test the solution
ob = Solution()
stacks = [
    [50, -4, -15],
    [2],
    [6, 7, 8]
]
k = 4
result = ob.solve(stacks, k)
print(f"Maximum sum with k={k} pops: {result}")
Maximum sum with k=4 pops: 39

How It Works

The algorithm explores all possible combinations:

  • Stack 1: [50, -4, -15] - We can pop 0, 1, 2, or 3 elements

  • Stack 2: [2] - We can pop 0 or 1 element

  • Stack 3: [6, 7, 8] - We can pop 0, 1, 2, or 3 elements

The optimal solution pops 3 elements from stack 1 (getting -15, -4, 50) and 1 element from stack 3 (getting 8), totaling 39.

Step-by-Step Trace

# Let's trace through the optimal path
stacks = [[50, -4, -15], [2], [6, 7, 8]]
k = 4

print("Optimal combination:")
print("From stack 1: pop 3 elements -> -15 + (-4) + 50 = 31")
print("From stack 2: pop 0 elements -> 0")
print("From stack 3: pop 1 element -> 8")
print("Total sum: 31 + 0 + 8 = 39")
Optimal combination:
From stack 1: pop 3 elements -> -15 + (-4) + 50 = 31
From stack 2: pop 0 elements -> 0
From stack 3: pop 1 element -> 8
Total sum: 31 + 0 + 8 = 39

Key Points

  • Recursive exploration: The function tries all valid combinations of popping elements

  • Base cases: Handle when exactly k elements are popped or invalid states

  • Stack constraint: Elements can only be popped from the top (end of list)

  • Optimization: Choose the combination that yields maximum sum

Conclusion

This solution uses recursive backtracking to explore all valid combinations of popping k elements from the stacks. The algorithm considers each stack and tries different numbers of pops, choosing the combination that maximizes the total sum.

Updated on: 2026-03-25T11:13:19+05:30

394 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements