Skip to content

2708. Maximum Strength of a Group 👍

  • Time: $O(n)$
  • Space: $O(1)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
class Solution {
 public:
  long long maxStrength(vector<int>& nums) {
    long long posProd = 1;
    long 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;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
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;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
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:  # num == 0
        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