152. Maximum Product Subarray

JJ·2021년 1월 24일
0

Algorithms

목록 보기
79/114
class Solution {
    public int maxProduct(int[] nums) {
        int result = nums[0];
        
        for (int i = 0; i < nums.length; i++) {
            int comp = 1;
            
            for (int j = i; j < nums.length; j++) {
                comp = comp * nums[j];
                
                result = Math.max(result, comp);
            }
        }
        
        return result; 
    }
}

Runtime: 98 ms, faster than 5.03% of Java online submissions for Maximum Product Subarray.
Memory Usage: 39.2 MB, less than 20.99% of Java online submissions for Maximum Product Subarray.

2중 for문이.. rg?^^

class Solution {
    public int maxProduct(int[] nums) {
        if (nums.length == 0) return 0;

        int max_so_far = nums[0];
        int min_so_far = nums[0];
        int result = max_so_far;

        for (int i = 1; i < nums.length; i++) {
            int curr = nums[i];
            int temp_max = Math.max(curr, Math.max(max_so_far * curr, min_so_far * curr));
            min_so_far = Math.min(curr, Math.min(max_so_far * curr, min_so_far * curr));

            max_so_far = temp_max;

            result = Math.max(max_so_far, result);
        }

        return result;
    }
}

Runtime: 1 ms, faster than 93.77% of Java online submissions for Maximum Product Subarray.
Memory Usage: 38.6 MB, less than 88.63% of Java online submissions for Maximum Product Subarray.
아름다운 루션이..

0개의 댓글

관련 채용 정보