Problem
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, where the strength of a group of students of indices i0
, i1
, i2
, … , ik
is defined as nums[i0] * nums[i1] * nums[i2] * ... * nums[ik]
.
Return the maximum strength of a group the teacher can create.
Example 1:
Input: nums = [3,-1,-5,2,5,-9]
Output: 1350
Explanation: One way to form a group of maximal strength is to group the students at indices [0,2,3,4,5]. Their strength is 3 * (-5) * 2 * 5 * (-9) = 1350, which we can show is optimal.
Example 2:
Input: nums = [-4,-5,-4]
Output: 20
Explanation: Group the students at indices [0, 1] . Then, we’ll have a resulting strength of 20. We cannot achieve greater strength.
Constraints:
1 <= nums.length <= 13
-9 <= nums[i] <= 9
Solution (Java)
import java.util.*;
class Solution {
public long maxStrength(int[] nums) {
int n = nums.length;
List<Long> negs = new ArrayList<>();
List<Long> pos = new ArrayList<>();
for (int num : nums) {
if (num < 0)
negs.add((long) num);
if (num > 0)
pos.add((long) num);
}
long prod = 1;
long x = Collections.frequency(Arrays.asList(nums), 0);
Collections.sort(negs);
if (negs.size() <= 1 && pos.size() == 0)
return Arrays.stream(nums).max().getAsInt();
if (negs.size() % 2 == 0) {
for (long num : negs)
prod = prod * num;
for (long num : pos)
prod = prod * num;
return prod;
} else {
for (int i = 0; i < negs.size() - 1; ++i)
prod = prod * negs.get(i);
for (long num : pos)
prod = prod * num;
return prod;
}
}
}
Explain:
nope.
Complexity:
- Time complexity : O(n).
- Space complexity : O(n).