Skip to content

2681. Power of Heroes 👍

  • Time: $O(\texttt{sort})$
  • Space: $O(\texttt{sort})$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
class Solution {
 public:
  int sumOfPower(vector<int>& nums) {
    constexpr int kMod = 1'000'000'007;
    long ans = 0;
    long sum = 0;

    ranges::sort(nums);

    for (const int num : nums) {
      ans = (ans + (num + sum) * num % kMod * num % kMod) % kMod;
      sum = (sum * 2 + num) % kMod;
    }

    return ans;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
class Solution {
  public int sumOfPower(int[] nums) {
    final int kMod = 1_000_000_007;
    long ans = 0;
    long sum = 0;

    Arrays.sort(nums);

    for (final int num : nums) {
      ans = (ans + (num + sum) * num % kMod * num % kMod) % kMod;
      sum = (sum * 2 + num) % kMod;
    }

    return (int) ans;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
class Solution:
  def sumOfPower(self, nums: list[int]) -> int:
    kMod = 1_000_000_007
    ans = 0
    summ = 0

    for num in sorted(nums):
      ans += (num + summ) * num**2
      ans %= kMod
      summ = (summ * 2 + num) % kMod

    return ans