Leetcode Problem
2708. Maximum Strength of a Group
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 i<sub>0</sub>
, i<sub>1</sub>
, i<sub>2</sub>
, ... , i<sub>k</sub>
is defined as nums[i<sub>0</sub>] * nums[i<sub>1</sub>] * nums[i<sub>2</sub>] * ... * nums[i<sub>k</sub>]
.
Input : nums = [3,-1,-5,2,5,-9]
long long maxStrength(vector<int>& nums)
{
int n=nums.size();
if(n==1)
{
return nums[0];
}
vector<int> pos;
vector<int> neg;
for(int i=0;i<n;i++)
{
if(nums[i]<0)
{
neg.push_back(nums[i]);
}
else
if(nums[i]>0)
{
pos.push_back(nums[i]);
}
}
sort(pos.begin(),pos.end());
sort(neg.begin(),neg.end());
long long ans1=0;
for(int i=0;i<neg.size();i++)
{
if(i==0)
{
ans1=neg[i];
}
else
{
if(neg.size()%2==0)
{
ans1=ans1*neg[i];
}
else
{
if(i<neg.size()-1)
{
ans1=ans1*neg[i];
}
}
}
}
long long ans2=0;
for(int i=0;i<pos.size();i++)
{
if(i==0)
{
ans2=pos[i];
}
else
{
ans2=ans2*pos[i];
}
}
if(ans1>0 && ans2>0)
return ans1*ans2;
else if(ans1>0)
return ans1;
else if(ans2>0)
return ans2;
else
return 0;
}