g2601_2700.s2681_power_of_heroes.Solution Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of leetcode-in-java21 Show documentation
Show all versions of leetcode-in-java21 Show documentation
Java-based LeetCode algorithm problem solutions, regularly updated
package g2601_2700.s2681_power_of_heroes;
// #Hard #Array #Math #Sorting #Prefix_Sum #2023_09_11_Time_13_ms_(88.24%)_Space_54.4_MB_(55.29%)
import java.util.Arrays;
/**
* 2681 - Power of Heroes\.
*
* Hard
*
* 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
.
*
* **Example 1:**
*
* **Input:** nums = [2,1,4]
*
* **Output:** 141
*
* **Explanation:**
*
* 1st group: [2] has power = 22 \* 2 = 8.
*
* 2nd group: [1] has power = 12 \* 1 = 1.
*
* 3rd group: [4] has power = 42 \* 4 = 64.
*
* 4th group: [2,1] has power = 22 \* 1 = 4.
*
* 5th group: [2,4] has power = 42 \* 2 = 32.
*
* 6th group: [1,4] has power = 42 \* 1 = 16.
*
* 7th group: [2,1,4] has power = 42 \* 1 = 16.
*
* The sum of powers of all groups is 8 + 1 + 64 + 4 + 32 + 16 + 16 = 141.
*
* **Example 2:**
*
* **Input:** nums = [1,1,1]
*
* **Output:** 7
*
* **Explanation:** A total of 7 groups are possible, and the power of each group will be 1. Therefore, the sum of the powers of all groups is 7.
*
* **Constraints:**
*
* * 1 <= nums.length <= 105
* * 1 <= nums[i] <= 109
**/
public class Solution {
public int sumOfPower(int[] nums) {
Arrays.sort(nums);
long sumOfMin = 0L;
long res = 0L;
for (int num : nums) {
long mod = 1_000_000_007L;
long max = (long) num * num % mod;
long mySumOfMin = (sumOfMin + num) % mod;
res = (res + max * mySumOfMin) % mod;
sumOfMin = (sumOfMin + mySumOfMin) % mod;
}
return (int) res;
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy