LeetCode 题解工作台
英雄的力量
给你一个下标从 0 开始的整数数组 nums ,它表示英雄的能力值。如果我们选出一部分英雄,这组英雄的 力量 定义为: i 0 , i 1 , ... i k 表示这组英雄在数组中的下标。那么这组英雄的力量为 max(nums[ i 0 ],nums[ i 1 ] ... nums[ i k ]) …
5
题型
5
代码语言
3
相关题
当前训练重点
困难 · 状态·转移·动态规划
答案摘要
我们注意到,题目中涉及到子序列的最大值和最小值,数组中元素的顺序不影响最终的结果,因此我们可以先对数组进行排序。 接下来,我们枚举每个元素作为子序列的最小值,不妨记数组的每个元素为 $a_1, a_2, \cdots, a_n$。以 作为最小值的子序列的贡献为:
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 状态·转移·动态规划 题型思路
题目描述
给你一个下标从 0 开始的整数数组 nums ,它表示英雄的能力值。如果我们选出一部分英雄,这组英雄的 力量 定义为:
i0,i1,...ik表示这组英雄在数组中的下标。那么这组英雄的力量为max(nums[i0],nums[i1] ... nums[ik])2 * min(nums[i0],nums[i1] ... nums[ik])。
请你返回所有可能的 非空 英雄组的 力量 之和。由于答案可能非常大,请你将结果对 109 + 7 取余。
示例 1:
输入:nums = [2,1,4] 输出:141 解释: 第 1 组:[2] 的力量为 22 * 2 = 8 。 第 2 组:[1] 的力量为 12 * 1 = 1 。 第 3 组:[4] 的力量为 42 * 4 = 64 。 第 4 组:[2,1] 的力量为 22 * 1 = 4 。 第 5 组:[2,4] 的力量为 42 * 2 = 32 。 第 6 组:[1,4] 的力量为 42 * 1 = 16 。 第 7 组:[2,1,4] 的力量为 42 * 1 = 16 。 所有英雄组的力量之和为 8 + 1 + 64 + 4 + 32 + 16 + 16 = 141 。
示例 2:
输入:nums = [1,1,1] 输出:7 解释:总共有 7 个英雄组,每一组的力量都是 1 。所以所有英雄组的力量之和为 7 。
提示:
1 <= nums.length <= 1051 <= nums[i] <= 109
解题思路
方法一:排序 + 数学
我们注意到,题目中涉及到子序列的最大值和最小值,数组中元素的顺序不影响最终的结果,因此我们可以先对数组进行排序。
接下来,我们枚举每个元素作为子序列的最小值,不妨记数组的每个元素为 。以 作为最小值的子序列的贡献为:
我们注意到,每一个 都会乘上 ,这一部分我们可以直接累加到答案中。剩下的部分,我们可以用一个变量 来维护,初始时 。
接下来从右往左枚举 ,每次我们将 累加到答案中,然后令 。
枚举完所有的 之后,返回答案即可。
时间复杂度 ,空间复杂度 。其中 为数组的长度。
class Solution:
def sumOfPower(self, nums: List[int]) -> int:
mod = 10**9 + 7
nums.sort()
ans = 0
p = 0
for x in nums[::-1]:
ans = (ans + (x * x % mod) * x) % mod
ans = (ans + x * p) % mod
p = (p * 2 + x * x) % mod
return ans
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | complexity is O(n log n) for sorting plus O(n) for DP iteration, giving O(n log n) overall. Space complexity is O(n) for storing DP states, though it can be optimized to O(1) with rolling variables. |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Sorting the array hints at a state transition dynamic programming solution.
- question_mark
Watch for integer overflow in calculations; modulo is essential.
- question_mark
Consider how each element contributes to all subsets including it.
常见陷阱
外企场景- error
Failing to account for modulo during each addition can cause overflow.
- error
Incorrectly calculating maximum or minimum in DP updates leads to wrong sums.
- error
Assuming subsets are independent without considering cumulative state leads to inefficiency.
进阶变体
外企场景- arrow_right_alt
Compute sum of hero group powers without modulo constraints, observing integer overflow.
- arrow_right_alt
Find the maximum single group power instead of sum of all groups using the same DP pattern.
- arrow_right_alt
Restrict groups to size k and sum powers using state transition DP optimized for fixed lengths.