[LeetCode] Power of Heroes

2681. Power of Heroes

You are given a 0-indexed integer array nums representing the strength of some heroes. The power of a group of heroes is defined as follows:

  • Let i0, i1, … ,ik be the indices of the heroes in a group. Then, the power of this group is max(nums[i0], nums[i1], ... ,nums[ik])2 * min(nums[i0], nums[i1], ... ,nums[ik]).

Return the sum of the power of all non-empty groups of heroes possible. Since the sum could be very large, return it modulo 109 + 7.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Solution {
public:
int sumOfPower(vector<int>& nums) {
sort(begin(nums), end(nums));
long long res = 0, mod = 1e9 + 7, sum = 0;
for(int i = 0; i < nums.size(); i++) {
long long ma = 1ll * nums[i] * nums[i] % mod;
if(i >= 2) sum = (sum + nums[i-2]) % mod * 2 % mod;
long long x = (sum + nums[i] + (i ? nums[i-1] : 0)) % mod;
res = (res + ma * x % mod) % mod;
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2023/05/13/PS/LeetCode/power-of-heroes/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.