Problem Description
Given an integer array nums representing the strength of some heroes, we define the power of any non-empty group of heroes as (maximum strength in the group)² multiplied by (minimum strength in the group). The task is to compute the sum of the power of every possible non-empty group of heroes modulo 10⁹ + 7.
Key Insights
- The brute force approach of enumerating all 2ⁿ - 1 subsets is infeasible for n up to 10⁵.
- Sorting the array (in non-decreasing order) allows us to treat any valid subset by its first (minimum) and last (maximum) element.
- For a fixed pair (i, j) with i ≤ j in the sorted array, any subset with minimum element nums[i] and maximum element nums[j] yields a contribution of nums[j]² * nums[i]. The number of such subsets (when i < j) is 2^(j-i-1). For i == j the contribution is simply nums[i]³.
- By reversing the double summation order and defining a helper cumulative value, we can derive a recurrence relation to aggregate the pair contributions in a single pass.
Space and Time Complexity
Time Complexity: O(n log n) (dominated by sorting) and O(n) for the linear pass.
Space Complexity: O(n) (for storing the sorted array, or O(1) extra space if sorting in-place).
Solution
The solution begins by sorting the array. Every individual hero (a single-element group) contributes its cube (nums[i]³) to the total sum. For groups with more than one element, consider the sorted order: let an element at index j serve as the maximum in the group. All valid minimum elements come from indices i (i < j), and for each such pair (i, j) the number of groups with that fixed minimum and maximum is 2^(j-i-1). Summing these contributions directly would be O(n²), so we define a cumulative variable g, where g(j) represents the weighted sum of candidates for the minimum when index j is the current maximum. With some algebra we derive the recurrence:
g(1) = nums[0]
g(j+1) = 2 * g(j) + nums[j]
Then, for each index j (from 1 to n-1), the contribution for the maximum element is: nums[j]² multiplied by g(j). Adding all these pair contributions with the single element contributions (the cubes) gives the final answer modulo 10⁹ + 7.