Leetcode Problem:
Summary
- Given a sorted array of integers, return the maximum between the number of positive integers and the number of negative integers.
Approach
- The approach used is to simply iterate through the array and count the number of positive and negative integers
- Then, return the maximum of the two counts.
Complexity
- O(n) where n is the number of elements in the array
Explanation
- The solution iterates through the array once, using a single loop to count the number of positive and negative integers
- The time complexity is linear because it only needs to examine each element once
- The space complexity is O(1) because it only uses a constant amount of space to store the counts.
Solution Code:
class Solution {
public:
int maximumCount(vector& nums) {
int minus = 0;
int plus = 0;
for(int i = 0 ; i < nums.size(); i++){
if(nums[i] < 0){
minus++;
}else if (nums[i] > 0){
plus++;
}
}
return max(minus, plus);
}
};
class Solution {
public:
int maximumCount(vector& nums) {
int minus = 0;
int plus = 0;
for(int i = 0 ; i < nums.size(); i++){
if(nums[i] < 0){
minus++;
}else if (nums[i] > 0){
plus++;
}
}
return max(minus, plus);
}
};
'알고리즘' 카테고리의 다른 글
House Robber IV (0) | 2025.03.15 |
---|---|
Zero Array Transformation II (0) | 2025.03.14 |
Number of Substrings Containing All Three Characters (0) | 2025.03.11 |
Count of Substrings Containing Every Vowel and K Consonants II (0) | 2025.03.10 |
Alternating Groups II (0) | 2025.03.10 |