LeetCode Entry

2529. Maximum Count of Positive Integer and Negative Integer

12.03.2025 easy 2025 kotlin rust

Max positive count or negative count search

2529. Maximum Count of Positive Integer and Negative Integer easy blog post substack youtube 1.webp

Join me on Telegram

https://t.me/leetcode_daily_unstoppable/925

Problem TLDR

Max positive count or negative count #easy #binary_search

Intuition

The brute-force is accepted. However, it is interesting to explore built-in solutions in each languages.

Approach

  • Kotlin: the shortest is a brute force, no built-in for array Binary Search
  • Rust: partition_point
  • c++: equal_range is the perfect match

Complexity

  • Time complexity: \(O(n)\) or O(log(n))

  • Space complexity: \(O(1)\)

Code


    fun maximumCount(nums: IntArray) =
        max(nums.count { it > 0 }, nums.count { it < 0 })


    fun maximumCount(nums: IntArray) = max(
        -nums.asList().binarySearch { if (it < 0) -1 else 1 } - 1,
        nums.size + nums.asList().binarySearch { if (it < 1) -1 else 1 } + 1)


    pub fn maximum_count(nums: Vec<i32>) -> i32 {
        let a = nums.partition_point(|&x| x < 0);
        let b = nums[a..].partition_point(|&x| x < 1);
        a.max(nums[a..].len() - b) as i32
    }


    int maximumCount(vector<int>& n) {
        auto [a, b] = equal_range(begin(n), end(n), 0);
        return max(distance(begin(n), a), distance(b, end(n)));
    }


    int maximumCount(vector<int>& nums) {
        int p = 0, n = 0;
        for (int x: nums) p += x > 0, n += x < 0;
        return max(p, n);
    }