#2708
Maximum Strength of a Group
MediumArrayDynamic ProgrammingBacktrackingGreedyBit ManipulationSortingEnumerationSortingGreedy
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n * 2^n) | O(n log n) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(n log n)Space O(1)
The optimal solution leverages sorting and the properties of multiplication. By sorting the array, we can efficiently determine the best combination of positive and negative numbers to maximize the product.
⚙️
Algorithm
5 steps- 1Step 1: Sort the array in non-decreasing order.
- 2Step 2: Initialize a product variable to 1 and a count of negative numbers to 0.
- 3Step 3: Iterate through the sorted array, multiplying positive numbers and counting negative numbers.
- 4Step 4: If there are an odd number of negative numbers, exclude the least negative number from the product.
- 5Step 5: If no positive numbers exist, return the maximum single negative number.
solution.py15 lines
1def maxStrength(nums):
2 nums.sort()
3 product = 1
4 negative_count = 0
5 max_negative = float('-inf')
6 for num in nums:
7 if num > 0:
8 product *= num
9 elif num < 0:
10 product *= num
11 negative_count += 1
12 max_negative = max(max_negative, num)
13 if negative_count % 2 == 1:
14 product //= max_negative
15 return product if product != 1 else max(max_negative, 0)ℹ
Complexity note: The time complexity is dominated by the sorting step (O(n log n)). The space complexity is constant as we only use a few variables.
- 1The product of an even number of negative numbers is positive, which can significantly increase the overall strength.
- 2Including all positive numbers is always beneficial as they increase the product.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.