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:

  1. Initialize a variable negCount to keep track of the number of negative numbers in the array.
  2. Iterate over each element num in the array nums.
  3. If num is equal to 0, return 0 as the product will be 0.
  4. If num is less than 0, increment negCount by 1.
  5. After iterating through all the elements, if negCount is even, return 1 as the product will be positive.
  6. 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:

  1. 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.
  2. Iterate over each element num in the array nums.
  3. 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.
  4. If num is less than 0, it means it is a negative number. We increment the negCount by 1 to keep track of the number of negative numbers encountered so far.
  5. 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.
  6. 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.