LeetCode 题解工作台
一个小组的最大实力值
给你一个下标从 0 开始的整数数组 nums ,它表示一个班级中所有学生在一次考试中的成绩。老师想选出一部分同学组成一个 非空 小组,且这个小组的 实力值 最大,如果这个小组里的学生下标为 i 0 , i 1 , i 2 , ... , i k ,那么这个小组的实力值定义为 nums[i 0 ] *…
7
题型
5
代码语言
3
相关题
当前训练重点
中等 · 状态·转移·动态规划
答案摘要
题目实际上是求所有子集的乘积的最大值,由于数组长度不超过 ,我们可以考虑使用二进制枚举的方法。 我们在 $[1, 2^n)$ 的范围内枚举所有的子集,对于每个子集,我们计算其乘积,最后返回最大值即可。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 状态·转移·动态规划 题型思路
题目描述
给你一个下标从 0 开始的整数数组 nums ,它表示一个班级中所有学生在一次考试中的成绩。老师想选出一部分同学组成一个 非空 小组,且这个小组的 实力值 最大,如果这个小组里的学生下标为 i0, i1, i2, ... , ik ,那么这个小组的实力值定义为 nums[i0] * nums[i1] * nums[i2] * ... * nums[ik] 。
请你返回老师创建的小组能得到的最大实力值为多少。
示例 1:
输入:nums = [3,-1,-5,2,5,-9] 输出:1350 解释:一种构成最大实力值小组的方案是选择下标为 [0,2,3,4,5] 的学生。实力值为 3 * (-5) * 2 * 5 * (-9) = 1350 ,这是可以得到的最大实力值。
示例 2:
输入:nums = [-4,-5,-4] 输出:20 解释:选择下标为 [0, 1] 的学生。得到的实力值为 20 。我们没法得到更大的实力值。
提示:
1 <= nums.length <= 13-9 <= nums[i] <= 9
解题思路
方法一:二进制枚举
题目实际上是求所有子集的乘积的最大值,由于数组长度不超过 ,我们可以考虑使用二进制枚举的方法。
我们在 的范围内枚举所有的子集,对于每个子集,我们计算其乘积,最后返回最大值即可。
时间复杂度 ,其中 是数组的长度。空间复杂度 。
class Solution:
def maxStrength(self, nums: List[int]) -> int:
ans = -inf
for i in range(1, 1 << len(nums)):
t = 1
for j, x in enumerate(nums):
if i >> j & 1:
t *= x
ans = max(ans, t)
return ans
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
The candidate demonstrates understanding of dynamic programming by implementing state transitions effectively.
- question_mark
The candidate optimizes subset evaluation to avoid redundant calculations, showing a good grasp of time complexity management.
- question_mark
The candidate exhibits proficiency in using backtracking to prune the search space and improve algorithm efficiency.
常见陷阱
外企场景- error
Failing to prune redundant calculations, which leads to inefficient solutions and long execution times.
- error
Not properly managing state transitions, causing incorrect results or excessive computations.
- error
Forgetting to account for the full range of possible subsets, leading to missing optimal solutions.
进阶变体
外企场景- arrow_right_alt
Consider larger input sizes and how the algorithm could scale with more students (larger nums array).
- arrow_right_alt
Optimize the space complexity by reducing the amount of state tracking used during dynamic programming transitions.
- arrow_right_alt
Adapt the solution for problems with different constraints, such as varying the score range or array length.