Leetcode 1822. Sign of the Product of an Array
You are given an integer array nums
. Let product
be the product of all values in the array nums
.
Return 1
if product
is positive, -1
if product
is negative, and 0
if product
is zero.
-100
and 100
.To determine the sign of the product of an array without actually computing the potentially large product, we can use the following approach:
0
.0
.-1
; if even, return 1
.#include <vector>
class Solution {
public:
int arraySign(std::vector<int>& nums) {
int negativeCount = 0;
for (int num : nums) {
if (num == 0) {
return 0;
} else if (num < 0) {
negativeCount++;
}
}
if (negativeCount % 2 == 0) {
return 1;
} else {
return -1;
}
}
};
n
is the number of elements in the array. This is because we are iterating over the array exactly once.Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?