#2681

Power of Heroes

Hard
ArrayMathDynamic ProgrammingSortingPrefix SumDynamic ProgrammingPrefix Sum
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n log n)
Space
O(1)
O(n)
💡

Intuition

Time O(n log n)Space O(n)

By sorting the array, we can efficiently calculate the contribution of each hero to the total power based on their position in the sorted order. This allows us to avoid generating all subsets explicitly.

⚙️

Algorithm

4 steps
  1. 1Step 1: Sort the array in non-decreasing order.
  2. 2Step 2: Initialize a total power variable and a prefix sum array to keep track of contributions.
  3. 3Step 3: For each hero in the sorted array, calculate how many times they will be the max and min in the groups they belong to.
  4. 4Step 4: Use the prefix sum to calculate the contributions of each hero efficiently.
solution.py16 lines
1# Full working Python code
2def sum_of_powers(nums):
3    MOD = 10**9 + 7
4    nums.sort()
5    total_power = 0
6    n = len(nums)
7    prefix_sum = 0
8
9    for i in range(n):
10        max_contrib = (nums[i] ** 2) * (pow(2, i, MOD) - 1)
11        min_contrib = nums[i] * prefix_sum * pow(2, n - i - 1, MOD)
12        total_power = (total_power + max_contrib - min_contrib) % MOD
13        prefix_sum = (prefix_sum + nums[i] * pow(2, i, MOD)) % MOD
14
15    return total_power
16

Complexity note: The time complexity is O(n log n) due to sorting the array, and O(n) for calculating contributions, making it efficient for large inputs.

  • 1Sorting the array allows for efficient calculation of contributions.
  • 2Using prefix sums helps in avoiding recomputation.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.