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.
Input: nums =[3,-1,-5,2,5,-9]Output: 1350Explanation: One way to form a group of maximal strength is to group the students at indices [0,2,3,4,5]. Their strength is3*(-5)*2*5*(-9)=1350, which we can show is optimal.
Input: nums =[-4,-5,-4]Output: 20Explanation: Group the students at indices [0,1]. Then, we'll have a resulting strength of 20. We cannot achieve greater strength.
To maximize the product (strength), we want to include as many positive numbers as possible and pair negative numbers to make their product positive. If there is an odd number of negatives, we can exclude the one with the smallest absolute value. If all numbers are negative and only one can be chosen, pick the largest (least negative).
classSolution {
public:longlong maxStrength(vector<int>& nums) {
vector<int> pos, neg;
for (int x : nums) {
if (x >0) pos.push_back(x);
elseif (x <0) neg.push_back(x);
}
sort(neg.begin(), neg.end());
if (neg.size() %2) neg.pop_back();
longlong ans =1;
bool used = false;
for (int x : pos) ans *= x, used = true;
for (int x : neg) ans *= x, used = true;
if (!used) return*max_element(nums.begin(), nums.end());
return ans;
}
};
classSolution {
publiclongmaxStrength(int[] nums) {
List<Integer> pos =new ArrayList<>(), neg =new ArrayList<>();
for (int x : nums) {
if (x > 0) pos.add(x);
elseif (x < 0) neg.add(x);
}
Collections.sort(neg);
if (neg.size() % 2 == 1) neg.remove(neg.size() - 1);
long ans = 1;
boolean used =false;
for (int x : pos) { ans *= x; used =true; }
for (int x : neg) { ans *= x; used =true; }
if (!used) {
int mx = nums[0];
for (int x : nums) mx = Math.max(mx, x);
return mx;
}
return ans;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
classSolution {
funmaxStrength(nums: IntArray): Long {
val pos = mutableListOf<Int>()
val neg = mutableListOf<Int>()
for (x in nums) {
if (x > 0) pos.add(x)
elseif (x < 0) neg.add(x)
}
neg.sort()
if (neg.size % 2==1) neg.removeAt(neg.size - 1)
var ans = 1Lvar used = falsefor (x in pos) { ans *= x; used = true }
for (x in neg) { ans *= x; used = true }
if (!used) return nums.maxOrNull()!!.toLong()
return ans
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
classSolution:
defmaxStrength(self, nums: list[int]) -> int:
pos = [x for x in nums if x >0]
neg = sorted([x for x in nums if x <0])
if len(neg) %2:
neg.pop()
ans, used =1, Falsefor x in pos:
ans *= x
used =Truefor x in neg:
ans *= x
used =Trueifnot used:
return max(nums)
return ans