[LeetCode] 152. Maximum Product Subarray

2023. 8. 26. 11:34·Problem Solving/LeetCode

 

출처 : https://leetcode.com/problems/maximum-product-subarray/description/

 

Maximum Product Subarray - LeetCode

Can you solve this real interview question? Maximum Product Subarray - Given an integer array nums, find a subarray that has the largest product, and return the product. The test cases are generated so that the answer will fit in a 32-bit integer.   Examp

leetcode.com

 

 

아래 코드는 브루트포스로 스스로 해결하였고, 아래 주석 코드는 투 포인터를 활용한 다른 사람 코드이다. 사실 시간이 그렇게 차이가 나지 않기 때문에 어떤 방법을 사용해도 무관하다는 생각이 들지만 다른 방식으로 접근해보는 것도 좋은 공부법이라고 생각한다. 

 

class Solution {
    public int maxProduct(int[] nums) {
        // 2ms : bruteforce
        int mx = nums[0], mn = nums[0], ans = nums[0];

        for(int i=1; i<nums.length; i++) {
            int tmp = mx;

            mx = Math.max(Math.max(mx * nums[i], mn * nums[i]), nums[i]);
            mn = Math.min(Math.min(tmp * nums[i], mn * nums[i]), nums[i]);
            
            if(mx > ans) ans = mx;
        }

        return ans;


        // 1ms : two pointer
        // int n = nums.length;
        // int l = 1, r = 1;
        // int ans = nums[0];

        // for(int i=0; i<n; i++) {
        //     l = l==0 ? 1 : l;
        //     r = r==0 ? 1 : r;

        //     l *= nums[i]; // prefix
        //     r *= nums[n-1-i]; // suffix

        //     ans = Math.max(ans, Math.max(l, r));
        // }
        // return ans;
    }
}
'Problem Solving/LeetCode' 카테고리의 다른 글
  • [LeetCode] 198. House Robber
  • [LeetCode] 238. Product of Array Except Self
  • [LeetCode] 36. Valid Sudoku
  • [LeetCode] 347. Top K Frequent Elements
kimdozzi
kimdozzi
끝까지 포기하지 않으면, 내가 다 이겨!
  • kimdozzi
    도브로
    kimdozzi
  • 전체
    오늘
    어제
    • 분류 전체보기 (132)
      • Problem Solving (49)
        • Baekjoon (29)
        • Programmers (0)
        • LeetCode (17)
        • 삼성 유형 (2)
      • Computer Science (27)
        • Operating System (2)
        • Algorithms (13)
        • Network (6)
        • DataBase (6)
      • Backend (33)
        • JavaScript (0)
        • TypeScript (6)
        • Java (7)
        • Spring Boot (7)
        • Spring Security (6)
        • JPA (2)
        • Mybatis (1)
        • Junit5 (1)
        • Redis (3)
      • DevOps (14)
        • Git, Github (5)
        • docker (4)
        • AWS (3)
        • nginx (2)
      • etc (6)
        • IntelliJ (3)
  • 블로그 메뉴

    • 홈
    • 태그
    • 방명록
    • 티스토리
    • 설정
  • 링크

  • 공지사항

  • 인기 글

  • 태그

    docker image
    PrefixSum
    타입스크립트
    알고리즘
    누적합
    AWS
    티스토리챌린지
    python
    백준
    파이썬
    Bucket
    삼성기출
    오블완
    docker
    interface
    컨테이너
    S3
    구간 업데이트
    TypeScript
    인덱스 시그니처
    imos법
    점 업데이트
    구간합
    인덱서블 타입
    인터페이스
    온라인 쿼리
    세그먼트 트리
    CORS
    오프라인 쿼리
    segment tree
    도커
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.0
kimdozzi
[LeetCode] 152. Maximum Product Subarray
상단으로

티스토리툴바