1822. Sign of the Product of an Array leetcode in c++
Problem Description:
Given an array of integers nums, find the product of the elements in the array and return the sign of the product.
The sign of the product is:
- 1 if the product is positive.
- -1 if the product is negative.
- 0 if the product is equal to 0.
Approach:
- Initialize a variable
negCount
to keep track of the number of negative numbers in the array. - Iterate over each element
num
in the arraynums
. - If
num
is equal to 0, return 0 as the product will be 0. - If
num
is less than 0, incrementnegCount
by 1. - After iterating through all the elements, if
negCount
is even, return 1 as the product will be positive. - Otherwise, return -1 as the product will be negative.
Pseudocode:
int arraySign(vector<int>& nums) {
int negCount = 0;
for (int num : nums) {
if (num == 0) {
return 0;
}
if (num < 0) {
negCount++;
}
}
return (negCount % 2 == 0) ? 1 : -1;
}
Explanation:
Let's go through the steps of the approach in more detail:
- Initialize a variable
negCount
to keep track of the number of negative numbers in the array. This variable will be used to determine the sign of the product. - Iterate over each element
num
in the arraynums
. - If
num
is equal to 0, it means the product will be 0. In this case, we can immediately return 0 as the product of any number with 0 is 0. - If
num
is less than 0, it means it is a negative number. We increment thenegCount
by 1 to keep track of the number of negative numbers encountered so far. - After iterating through all the elements, we need to determine the sign of the product. If the
negCount
is even, it means there are an even number of negative numbers, and thus the product will be positive. In this case, we can return 1. - If the
negCount
is odd, it means there are an odd number of negative numbers, and thus the product will be negative. In this case, we can return -1.
The pseudocode provided above implements the approach described. The function arraySign
takes an input array nums
and returns the sign of the product of its elements.