You are given a 0-indexed integer array nums representing the strength of some heroes.…
- User
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
TESTCASE: [2,1,4]
- Assistant
Approach:
- Find all the possible subsets of given list.
- calculate the power for each subset and add to result.
- return result mod (10^9 + 7)
Algorithm:
-
calculate power of a subset. 1.1. get maximum from subset. square it. 1.2. get minimum from subset. Multiply with result of step 1.1 1.3. return result of step 1.2
-
create empty list result.
-
create all possible subsets of given list. for each subset do the following. 3.1. use function from step 1 to calculate power of given subset. 3.2. add result from step 3.1 to result list.
-
return sum of result list mod (10^9 + 7).
Complxity Analysis:
- Time complexity: generating all possible subsets is O(2^n). You will have to calculate power for each subset. so Total time complexity would be O(2^n * n).
- Space complexity: O(2^n) as result list can have maximum 2^n elements.
- User
give me the python code
- Assistant
Here's the Python code based on the above approach:
codeclass Solution: def maxProduct(self, nums: List[int]) -> int: MOD = 10**9 + 7 # function to calculate power of given subset def calculate_power(subset): max_num = max(subset) min_num = min(subset) return (max_num**2 * min_num) % MOD # generate all possible subsets n = len(nums) result = [] for mask in range(1, 2**n): # generate mask for all possible subsets subset = [] for i in range(n): if (1 << i) & mask: # check if i-th bit is set in mask subset.append(nums[i]) result.append(calculate_power(subset)) # calculate power of the subset and add to result list # return sum of all powers mod (10^9 + 7) return sum(result) % MOD