Program to find sum of the minimums of each sublist from a list in Python

Suppose we have a list of numbers called nums. We have to find the sum of minimum values for every possible sublist in nums. If the answer is too large, then mod the result by 10^9 + 7.

So, if the input is like nums = [5, 10, 20, 10, 0], then the output will be 90 because the sublists are [[5], [10], [20], [10], [0], [5,10], [10,20], [20,10], [10,0], [5,10,20], [10,20,10], [20,10,0], [5,10,20,10], [10,20,10,0], [5,10,20,10,0]], and their minimum values are [5, 10, 20, 10, 0, 5, 10, 10, 0, 5, 10, 0, 5, 0, 0], so the sum is 90.

Algorithm

To solve this efficiently, we will follow these steps ?

  • Initialize ans := 0, stack := empty list, temp_sum := 0
  • For each index and value in nums, do:
    • While stack is not empty and current value ? top element's value, remove elements from stack and update temp_sum
    • If stack is empty, add [index, value, (index + 1) * value] to stack
    • Otherwise, add [index, value, (index ? last_element_index) * value] to stack
    • Update temp_sum and add it to ans
  • Return ans mod (10^9 + 7)

Example

Let us see the following implementation to get better understanding ?

def solve(nums):
    ans = 0
    stack = []
    temp_sum = 0
    
    for index, value in enumerate(nums):
        # Remove elements from stack that are greater than current value
        while stack and value <= stack[-1][1]:
            temp_sum -= stack[-1][2]
            stack.pop()
        
        # Add current element to stack
        if not stack:
            stack.append([index, value, (index + 1) * value])
        else:
            stack.append([index, value, (index - stack[-1][0]) * value])
        
        # Update temp_sum and add to answer
        temp_sum += stack[-1][2]
        ans += temp_sum
    
    return ans % (10**9 + 7)

# Test the function
nums = [5, 10, 20, 10, 0]
result = solve(nums)
print(f"Input: {nums}")
print(f"Sum of minimums of all sublists: {result}")
Input: [5, 10, 20, 10, 0]
Sum of minimums of all sublists: 90

How It Works

The algorithm uses a monotonic stack to efficiently calculate the contribution of each element as a minimum in various sublists. For each element, we determine how many sublists it will be the minimum element of, and multiply accordingly.

Step-by-Step Execution

def solve_with_steps(nums):
    ans = 0
    stack = []
    temp_sum = 0
    
    print(f"Processing array: {nums}")
    print("-" * 50)
    
    for index, value in enumerate(nums):
        print(f"\nStep {index + 1}: Processing element {value} at index {index}")
        
        # Remove elements from stack
        while stack and value <= stack[-1][1]:
            removed = stack.pop()
            temp_sum -= removed[2]
            print(f"  Removed {removed} from stack")
        
        # Add current element
        if not stack:
            contribution = (index + 1) * value
            stack.append([index, value, contribution])
            print(f"  Added [{index}, {value}, {contribution}] to empty stack")
        else:
            contribution = (index - stack[-1][0]) * value
            stack.append([index, value, contribution])
            print(f"  Added [{index}, {value}, {contribution}] to stack")
        
        temp_sum += stack[-1][2]
        ans += temp_sum
        
        print(f"  Stack: {stack}")
        print(f"  temp_sum: {temp_sum}, ans: {ans}")
    
    return ans % (10**9 + 7)

# Demonstrate step-by-step execution
nums = [5, 10, 20, 10, 0]
result = solve_with_steps(nums)
print(f"\nFinal result: {result}")
Processing array: [5, 10, 20, 10, 0]
--------------------------------------------------

Step 1: Processing element 5 at index 0
  Added [0, 5, 5] to empty stack
  Stack: [[0, 5, 5]]
  temp_sum: 5, ans: 5

Step 2: Processing element 10 at index 1
  Added [1, 10, 10] to stack
  Stack: [[0, 5, 5], [1, 10, 10]]
  temp_sum: 15, ans: 20

Step 3: Processing element 20 at index 2
  Added [2, 20, 20] to stack
  Stack: [[0, 5, 5], [1, 10, 10], [2, 20, 20]]
  temp_sum: 35, ans: 55

Step 4: Processing element 10 at index 3
  Removed [2, 20, 20] from stack
  Added [3, 10, 20] to stack
  Stack: [[0, 5, 5], [1, 10, 10], [3, 10, 20]]
  temp_sum: 35, ans: 90

Step 5: Processing element 0 at index 4
  Removed [3, 10, 20] from stack
  Removed [1, 10, 10] from stack
  Removed [0, 5, 5] from stack
  Added [4, 0, 0] to empty stack
  Stack: [[4, 0, 0]]
  temp_sum: 0, ans: 90

Final result: 90

Conclusion

This algorithm efficiently calculates the sum of minimums of all sublists using a monotonic stack approach in O(n) time complexity. The key insight is tracking how many sublists each element serves as the minimum element for, avoiding the brute force O(n³) approach.

Updated on: 2026-03-26T17:14:12+05:30

367 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements