Skip to content

Latest commit

Β 

History

History
57 lines (53 loc) Β· 1.75 KB

File metadata and controls

57 lines (53 loc) Β· 1.75 KB
class Solution {
    public int maxProduct(int[] nums) {
        int max = Integer.MIN_VALUE;
        int temp = 0;
        int lastZeroIndex = 0;
        for (int i = 0; i < nums.length; i++) {
            int current = nums[i];
            if (temp == 0) {
                temp = current;
                lastZeroIndex = i;
            } else {
                if (current == 0) {
                    temp = 0;
                } else if (temp > 0 && current < 0) {
                    if (hasNextMinus(nums, i + 1)) {
                        temp = temp * current;
                    } else {
                        temp = temp * current;
                        for (int j = lastZeroIndex; j < i + 1; j++) {
                            temp = temp / nums[j];
                            if (temp > 0) {
                                break;
                            }
                        }
                    }
                } else {
                    temp = temp * current;
                }
            }
            max = Math.max(max, temp);
            if (temp < 0 && !hasNextMinus(nums, i + 1)) {
                temp = 0;
            }
        }
        return max;
    }

    private boolean hasNextMinus(int[] nums, int i) {
        for (; i < nums.length; i++) {
            if (nums[i] < 0) {
                return true;
            } else if (nums[i] == 0) {
                return false;
            }
        }
        return false;
    }
}

TC, SC

μ‹œκ°„ λ³΅μž‘λ„λŠ” O(n^2)이닀. 곡간 λ³΅μž‘λ„λŠ” O(1)이닀. hasNextMinus 이 적게 ν˜ΈμΆœλœλ‹€λ©΄ μ‹œκ°„ λ³΅μž‘λ„λŠ” O(n)에 κ°€κΉκ²Œ λ™μž‘ν•œλ‹€.