You are given a 0-indexed integer array nums representing the score of students in an exam. The teacher would like to form one non-empty group of students with maximal strength.

The strength of a group of students at indices i₀, i₁, i₂, ..., iₖ is defined as:

nums[i₀] × nums[i₁] × nums[i₂] × ... × nums[iₖ]

Return the maximum strength of a group the teacher can create.

Input & Output

Example 1 — Mixed Positive and Negative
$ Input: nums = [3,-1,-5,2]
Output: 30
💡 Note: We can form the group [3,-1,-5,2]. The strength is 3 × (-1) × (-5) × 2 = 30. This is optimal since all elements can be included.
Example 2 — Single Element
$ Input: nums = [-4]
Output: -4
💡 Note: Since we must form a non-empty group and there's only one element, we must choose [-4] with strength -4.
Example 3 — All Negative with Odd Count
$ Input: nums = [-1,-2,-3]
Output: 6
💡 Note: The best group is [-2,-3] with strength (-2) × (-3) = 6. Including -1 would make the product negative.

Constraints

  • 1 ≤ nums.length ≤ 13
  • -9 ≤ nums[i] ≤ 9

Visualization

Tap to expand
Maximum Strength of a Group INPUT nums array: 3 i=0 -1 i=1 -5 i=2 2 i=3 Categorize Numbers: Positive 3, 2 Negative -1, -5 Input: nums = [3, -1, -5, 2] ALGORITHM STEPS 1 Separate numbers Split into +ve and -ve 2 Pair negatives (-1) x (-5) = 5 3 Include all positives 3 x 2 = 6 4 Multiply all selected 6 x 5 = 30 Greedy Selection: Positives: 3 x 2 = 6 Neg pairs: (-1)x(-5) = 5 Total: 6 x 5 = 30 Time: O(n) | Space: O(1) FINAL RESULT Selected Group: 3 -1 -5 2 All elements selected! Strength Calculation: 3 x (-1) x (-5) x 2 = 3 x 5 x 2 = 30 Output: 30 OK - Maximum Strength! Key Insight: The greedy approach maximizes product by: 1) Including all positive numbers, 2) Pairing negative numbers (two negatives make positive), 3) Excluding odd negative with smallest absolute value. Product of paired negatives always increases strength! TutorialsPoint - Maximum Strength of a Group | Greedy Approach
Asked in
Meta 3 Google 2
8.9K Views
Medium Frequency
~15 min Avg. Time
245 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