Problem Solving

1567. Maximum Length of Subarray With Positive Product

enumclass 2020. 9. 1. 14:49

Maximum Length of Subarray With Positive Product

 

곱셈의 법칙을 적절히 이용해야 한다. 짝수의 음수는 반듯이 짝수고 홀수개의 음수는 음수 이기 때문에 여기서 하나의 음수를 빼면 다시 짝수가 된다. 

- 3개의 음수가 있으면 첫번째 음수를 제외하고 계산하면 되고

- 2개의 음수가 있으면 짝수처럼 처리 하면 된다.

var getMaxLen = function(nums) {
    let firstNegative = -1;
    let zeroPosition = -1;
    let negativeCount = 0;
    let max = 0;
    
    for(let i = 0; i < nums.length; i++){
        if(nums[i] < 0){
            if(firstNegative < 0) {
                firstNegative = i;
            }
            negativeCount++;
        }
        
        if(nums[i] == 0){
            firstNegative = -1;
            zeroPosition = i;
            negativeCount = 0;
        } else {
            if(negativeCount%2){
                max = Math.max(max,i - firstNegative);
            } else {
                max = Math.max(max,i - zeroPosition);
            }
        }
    }
    
    return max;
};

O(N), O(1)

728x90
반응형