2681. Power of Heroes

2681. 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.

class Solution {
public:
    int sumOfPower(vector<int>& nums) {
        long long res = 0, s = 0, base = 1e9 + 7;
        sort(nums.begin(), nums.end());
        for (int x: nums) {
            res = (res + (s + x) * x % base * x % base) % base;
            s = (s * 2 + x) % base;
        }
        return res;
    }
};