A teacher wants to form the strongest possible study group from students based on their exam scores! ๐Ÿ“š

Given a 0-indexed integer array nums representing student scores, you need to select any non-empty subset of students to maximize the group's strength.

The strength of a group is calculated by multiplying all selected scores together. For example, if you select students with scores [2, -3, 4], the strength would be 2 ร— (-3) ร— 4 = -24.

Goal: Return the maximum possible strength you can achieve by selecting the optimal group of students.

Key Insight: Since we're dealing with multiplication, negative numbers can become positive when paired together, and we want to maximize the final product!

Input & Output

example_1.py โ€” Basic positive case
$ Input: [3, -1, -2]
โ€บ Output: 6
๐Ÿ’ก Note: We can select all elements: 3 ร— (-1) ร— (-2) = 6. The two negatives multiply to positive.
example_2.py โ€” Mixed with zero
$ Input: [-4, -5, -4]
โ€บ Output: 20
๐Ÿ’ก Note: Select [-4, -5] to get (-4) ร— (-5) = 20. Avoid the third -4 to keep result positive.
example_3.py โ€” All negative
$ Input: [-1, -2, -3]
โ€บ Output: 6
๐Ÿ’ก Note: Select [-2, -3] to get (-2) ร— (-3) = 6. Exclude -1 to avoid negative result.

Constraints

  • 1 โ‰ค nums.length โ‰ค 13
  • -9 โ‰ค nums[i] โ‰ค 9
  • Note: Small constraints allow for brute force solutions

Visualization

Tap to expand
๐Ÿ† Maximum Team Strength Strategy+3Always Include+4Always Include-1Pair Up-2Pair Up(-1) ร— (-2) = +2Final CalculationPositives: 3 ร— 4 = 12Negatives: (-1) ร— (-2) = 2Total: 12 ร— 2 = 24โœ… All positives includedโœ… Even number of negativesโœ… No zeros needed
Understanding the Visualization
1
Sort by Type
Categorize team members by power type (positive/negative/zero)
2
Include Positives
All positive powers boost the team strength
3
Pair Negatives
Two negative powers cancel out to become positive
4
Strategic Zeros
Use zero-power members to prevent negative team strength
Key Takeaway
๐ŸŽฏ Key Insight: Multiplication allows us to turn negatives into positives by pairing them up, while zeros act as a safety net to prevent negative results.
Asked in
Google 42 Amazon 38 Meta 31 Microsoft 25
42.3K Views
Medium Frequency
~15 min Avg. Time
1.8K Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen