짬뽕얼큰하게의 맨땅에 헤딩 :: Maximum Count of Positive Integer and Negative Integer

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);
    }
};
블로그 이미지

짬뽕얼큰하게

,