Skip to content

Commit

Permalink
New Problem Solution - "1822. Sign of the Product of an Array"
Browse files Browse the repository at this point in the history
  • Loading branch information
haoel committed Apr 11, 2021
1 parent 1629a81 commit d26ba3a
Show file tree
Hide file tree
Showing 2 changed files with 52 additions and 0 deletions.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ LeetCode

| # | Title | Solution | Difficulty |
|---| ----- | -------- | ---------- |
|1822|[Sign of the Product of an Array](https://leetcode.com/problems/sign-of-the-product-of-an-array/) | [C++](./algorithms/cpp/signOfTheProductOfAnArray/SignOfTheProductOfAnArray.cpp)|Easy|
|1819|[Number of Different Subsequences GCDs](https://leetcode.com/problems/number-of-different-subsequences-gcds/) | [C++](./algorithms/cpp/numberOfDifferentSubsequencesGcds/NumberOfDifferentSubsequencesGcds.cpp)|Hard|
|1818|[Minimum Absolute Sum Difference](https://leetcode.com/problems/minimum-absolute-sum-difference/) | [C++](./algorithms/cpp/minimumAbsoluteSumDifference/MinimumAbsoluteSumDifference.cpp)|Medium|
|1817|[Finding the Users Active Minutes](https://leetcode.com/problems/finding-the-users-active-minutes/) | [C++](./algorithms/cpp/findingTheUsersActiveMinutes/FindingTheUsersActiveMinutes.cpp)|Medium|
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
// Source : https://leetcode.com/problems/sign-of-the-product-of-an-array/
// Author : Hao Chen
// Date : 2021-04-11

/*****************************************************************************************************
*
* There is a function signFunc(x) that returns:
*
* 1 if x is positive.
* -1 if x is negative.
* 0 if x is equal to 0.
*
* You are given an integer array nums. Let product be the product of all values in the array nums.
*
* Return signFunc(product).
*
* Example 1:
*
* Input: nums = [-1,-2,-3,-4,3,2,1]
* Output: 1
* Explanation: The product of all values in the array is 144, and signFunc(144) = 1
*
* Example 2:
*
* Input: nums = [1,5,0,2,-3]
* Output: 0
* Explanation: The product of all values in the array is 0, and signFunc(0) = 0
*
* Example 3:
*
* Input: nums = [-1,1,-1,1,-1]
* Output: -1
* Explanation: The product of all values in the array is -1, and signFunc(-1) = -1
*
* Constraints:
*
* 1 <= nums.length <= 1000
* -100 <= nums[i] <= 100
******************************************************************************************************/

class Solution {
public:
int arraySign(vector<int>& nums) {
int negtive=0;
for(auto& n : nums) {
if (n==0) return 0;
if (n < 0) negtive++;
}
return negtive % 2 == 0 ? 1 : -1;
}
};

0 comments on commit d26ba3a

Please sign in to comment.