Power of Heroes - Problem
Power of Heroes is a challenging problem that requires calculating the sum of powers for all possible groups of heroes.
You are given a
For any group with indices
Goal: Return the sum of the power of all non-empty groups of heroes possible. Since the sum could be very large, return it modulo
This problem tests your understanding of mathematical optimization, sorting techniques, and efficient computation of subset contributions.
You are given a
0-indexed integer array nums representing the strength of some heroes. The power of a group of heroes is defined by a unique formula:For any group with indices
i0, i1, ..., ik, the power is:max(nums[i0], nums[i1], ..., nums[ik])² × min(nums[i0], nums[i1], ..., nums[ik])Goal: Return the sum of the power of all non-empty groups of heroes possible. Since the sum could be very large, return it modulo
10⁹ + 7.This problem tests your understanding of mathematical optimization, sorting techniques, and efficient computation of subset contributions.
Input & Output
example_1.py — Basic Example
$
Input:
nums = [2, 1, 4]
›
Output:
141
💡 Note:
All possible non-empty groups: {2}: 2² × 2 = 8, {1}: 1² × 1 = 1, {4}: 4² × 4 = 64, {2,1}: 2² × 1 = 4, {2,4}: 4² × 2 = 32, {1,4}: 4² × 1 = 16, {2,1,4}: 4² × 1 = 16. Total sum = 8+1+64+4+32+16+16 = 141
example_2.py — All Same Elements
$
Input:
nums = [1, 1, 1]
›
Output:
7
💡 Note:
Since all elements are the same, every group has power = 1² × 1 = 1. There are 2³ - 1 = 7 non-empty groups, so total sum = 7
example_3.py — Single Element
$
Input:
nums = [15]
›
Output:
3375
💡 Note:
Only one possible group: {15}. Power = 15² × 15 = 225 × 15 = 3375
Constraints
- 1 ≤ nums.length ≤ 105
- 1 ≤ nums[i] ≤ 106
- Result must be returned modulo 109 + 7
Visualization
Tap to expand
Understanding the Visualization
1
Sort Heroes by Strength
Arrange heroes in ascending order to identify contribution patterns
2
Calculate Each Hero's Maximum Contribution
For each hero, determine their contribution when they're the strongest in various teams
3
Use Mathematical Formulas
Apply prefix sums and powers of 2 to avoid brute force enumeration
4
Apply Modular Arithmetic
Handle large numbers using modulo 10^9 + 7 throughout calculations
Key Takeaway
🎯 Key Insight: By sorting first and using mathematical formulas, we transform an exponential problem into a linear one, calculating each element's contribution pattern instead of generating all possible subsets.
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code