Problem: 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 `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.


Python solution:
import math
import itertools
import bisect
import collections
import string
import heapq
import functools
import sortedcontainers
from typing import List, Dict, Tuple, Iterator

class Solution:
  def maxStrength(self, nums: List[int]) -> int:
    posProd = 1
    negProd = 1
    maxNeg = -math.inf
    negCount = 0
    hasPos = False
    hasZero = False

    for num in nums:
      if num > 0:
        posProd *= num
        hasPos = True
      elif num < 0:
        negProd *= num
        maxNeg = max(maxNeg, num)
        negCount += 1
      else:
        hasZero = True

    if negCount == 0 and not hasPos:
      return 0
    if negCount % 2 == 0:
      return negProd * posProd
    if negCount >= 3:
      return negProd // maxNeg * posProd
    if hasPos:
      return posProd
    if hasZero:
      return 0
    return maxNeg


Java solution:
class Solution {
  public long maxStrength(int[] nums) {
    long posProd = 1;
    long negProd = 1;
    int maxNeg = Integer.MIN_VALUE;
    int negCount = 0;
    boolean hasPos = false;
    boolean hasZero = false;

    for (final int num : nums)
      if (num > 0) {
        posProd *= num;
        hasPos = true;
      } else if (num < 0) {
        negProd *= num;
        maxNeg = Math.max(maxNeg, num);
        ++negCount;
      } else { // num == 0
        hasZero = true;
      }

    if (negCount == 0 && !hasPos)
      return 0;
    if (negCount % 2 == 0)
      return negProd * posProd;
    if (negCount >= 3)
      return negProd / maxNeg * posProd;
    if (hasPos)
      return posProd;
    if (hasZero)
      return 0;
    return maxNeg;
  }
}


C++ solution:
class Solution {
 public:
  long long maxStrength(vector<int>& nums) {
    long posProd = 1;
    long negProd = 1;
    int maxNeg = INT_MIN;
    int negCount = 0;
    bool hasPos = false;
    bool hasZero = false;

    for (const int num : nums)
      if (num > 0) {
        posProd *= num;
        hasPos = true;
      } else if (num < 0) {
        negProd *= num;
        maxNeg = max(maxNeg, num);
        ++negCount;
      } else {  // num == 0
        hasZero = true;
      }

    if (negCount == 0 && !hasPos)
      return 0;
    if (negCount % 2 == 0)
      return negProd * posProd;
    if (negCount >= 3)
      return negProd / maxNeg * posProd;
    if (hasPos)
      return posProd;
    if (hasZero)
      return 0;
    return maxNeg;
  }
};