LeetCode 题解工作台

一个小组的最大实力值

给你一个下标从 0 开始的整数数组 nums ,它表示一个班级中所有学生在一次考试中的成绩。老师想选出一部分同学组成一个 非空 小组,且这个小组的 实力值 最大,如果这个小组里的学生下标为 i 0 , i 1 , i 2 , ... , i k ,那么这个小组的实力值定义为 nums[i 0 ] *…

category

7

题型

code_blocks

5

代码语言

hub

3

相关题

当前训练重点

中等 · 状态·转移·动态规划

bolt

答案摘要

题目实际上是求所有子集的乘积的最大值,由于数组长度不超过 ,我们可以考虑使用二进制枚举的方法。 我们在 $[1, 2^n)$ 的范围内枚举所有的子集,对于每个子集,我们计算其乘积,最后返回最大值即可。

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 状态·转移·动态规划 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

给你一个下标从 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
lightbulb

解题思路

方法一:二进制枚举

题目实际上是求所有子集的乘积的最大值,由于数组长度不超过 1313,我们可以考虑使用二进制枚举的方法。

我们在 [1,2n)[1, 2^n) 的范围内枚举所有的子集,对于每个子集,我们计算其乘积,最后返回最大值即可。

时间复杂度 O(2n×n)O(2^n \times n),其中 nn 是数组的长度。空间复杂度 O(1)O(1)

1
2
3
4
5
6
7
8
9
10
11
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
speed

复杂度分析

指标
时间Depends on the final approach
空间Depends on the final approach
psychology

面试官常问的追问

外企场景
  • 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.

warning

常见陷阱

外企场景
  • 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.

swap_horiz

进阶变体

外企场景
  • 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.

help

常见问题

外企场景

一个小组的最大实力值题解:状态·转移·动态规划 | LeetCode #2708 中等