Sponsored
Sponsored
This approach involves scanning through the array once to check for any zeros and counting the number of negative numbers. If there's a zero, the product is zero. Otherwise, if the number of negative numbers is odd, the product is negative; if even, the product is positive.
Time Complexity: O(n), where n is the number of elements in the array. We only need to pass over the array once.
Space Complexity: O(1), as no additional space beyond the given variables is used.
1#include <vector>
2using namespace std;
3
4int arraySign(vector<int>& nums) {
5 int negative_count = 0;
6 for (int num : nums) {
7 if (num == 0) return 0;
8 if (num < 0) negative_count++;
9 }
10 return (negative_count % 2 == 0) ? 1 : -1;
11}
12
13int main() {
14 vector<int> nums = {-1, -2, -3, -4, 3, 2, 1};
15 printf("%d\n", arraySign(nums));
16 return 0;
17}
The C++ solution follows the same logic as the C solution but makes use of C++ STL features. The numerical values from vector <int> can be directly iterated over using a range-based for loop.
This approach uses a multiplicative identity set as variable 'sign', initialized to 1. Then iterates through each element of the array, multiplying 'sign' with -1 for each negative number and returning zero if a zero is found.
Time Complexity: O(n)
Space Complexity: O(1)
1
This C code sets a 'sign' variable to 1 and iterates over the input. It flips the sign by multiplying it by -1 for each negative number found, returning 0 immediately upon encountering a zero.