Leetcode 2529. Maximum Count of Positive Integer and Negative Integer
You are given an array containing both positive and negative integers. Your task is to find the maximum count of either strictly positive or strictly negative integers.
In other words, you should return the count of the majority of the integers in the array. If the counts of positive and negative integers are the same, return that count.
positiveCount
) and one for counting negative integers (negativeCount
).positiveCount
.negativeCount
.public class Solution {
public int maximumCount(int[] nums) {
int positiveCount = 0;
int negativeCount = 0;
for (int num : nums) {
if (num > 0) {
positiveCount++;
} else if (num < 0) {
negativeCount++;
}
}
return Math.max(positiveCount, negativeCount);
}
public static void main(String[] args) {
Solution sol = new Solution();
int[] nums1 = {1, -2, 3, -4, 5, -6}; // Expected output: 3 (there are 3 positive integers and 3 negative integers)
int[] nums2 = {-1, -2, -3, -4, -5}; // Expected output: 5 (there are 5 negative integers)
int[] nums3 = {1, 2, 3, 4, 5}; // Expected output: 5 (there are 5 positive integers)
int[] nums4 = {0, 0, 0}; // Expected output: 0 (there are no positive or negative integers)
System.out.println(sol.maximumCount(nums1)); // 3
System.out.println(sol.maximumCount(nums2)); // 5
System.out.println(sol.maximumCount(nums3)); // 5
System.out.println(sol.maximumCount(nums4)); // 0
}
}
By following this approach, we ensure that the solution is both efficient and easy to understand.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?