LeetCode 2681: Power of Heroes
Problem Description
Explanation:
To solve this problem, we can iterate through all possible groups of heroes and calculate the power of each group according to the given formula. We need to find the maximum and minimum strength within each group and then calculate the power. Finally, we sum up the powers of all non-empty groups and return the result modulo 10^9 + 7.
Here is the algorithm:
- Initialize a variable
result
to store the sum of powers of all groups. - Iterate through all possible groups of heroes using nested loops.
- For each group, find the maximum and minimum strength within the group.
- Calculate the power of the group using the formula: (max_strength^2 * min_strength) % (10^9 + 7).
- Add the calculated power to the
result
. - Return the
result
modulo 10^9 + 7 as the final answer.
:
Solutions
class Solution {
public int powerOfHeroes(int[] nums) {
int mod = (int) 1e9 + 7;
long result = 0;
for (int i = 0; i < nums.length; i++) {
long maxStrength = nums[i];
long minStrength = nums[i];
for (int j = i; j < nums.length; j++) {
maxStrength = Math.max(maxStrength, nums[j]);
minStrength = Math.min(minStrength, nums[j]);
result = (result + (maxStrength * maxStrength % mod) * minStrength % mod) % mod;
}
}
return (int) result;
}
}
Loading editor...