[PS] Leet | 152. 최댓값을 가지는 하위 배열 - 곱셈

2025. 3. 20. 00:30·CS/PS

문제

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.

예시

Example 1:
Input: nums = [2,3,-2,4]
Output: 6
Explanation: [2,3] has the largest product 6.


Example 2:
Input: nums = [-2,0,-1]
Output: 0
Explanation: The result cannot be 2, because [-2,-1] is not a subarray.

조건

  • 1 <= nums.length <= 2 * 104
  • -10 <= nums[i] <= 10
  • The product of any subarray of nums is guaranteed to fit in a 32-bit integer.

답

배열 안에 음수도 섞여 있기 때문에, 부호가 바뀌는 것을 고려하여 절댓값이 최소인 경우도 함께 고려해야 합니다.

 

절댓값이 최대인 경우(maxProduct)와 최소인 경우(minProduct)를 함께 갱신하면서, 음수인 숫자가 나오면 두 수를 뒤바꿉니다.

 

첫 요소가 양수인 경우 maxProduct가, 음수인 경우 minProduct가 최댓값을 추적합니다.

/**
 * @param {number[]} nums
 * @return {number}
 */
var maxProduct = function(nums) {
    let maxProduct = nums[0];
    let minProduct = nums[0];
    let totalMaxProduct = nums[0];

    for (let i=1; i<nums.length; ++i) {
        if (nums[i] < 0) {
            [maxProduct, minProduct] = [minProduct, maxProduct];
        }

        if (nums[i] === 0) {
            [maxProduct, minProduct] = [0, 0];
        }

        maxProduct = Math.max(nums[i], maxProduct * nums[i]);
        minProduct = Math.min(nums[i], minProduct * nums[i]);

        totalMaxProduct = Math.max(totalMaxProduct, maxProduct);
    }

    return totalMaxProduct;
};
728x90

'CS > PS' 카테고리의 다른 글

[PS] 가장 가까운 두 수  (0) 2025.03.21
[PS] Leet | 33. 정렬된 회전 배열에서의 탐색  (0) 2025.03.20
[PS] Leet | 153. 정렬된 회전배열에서의 최소값  (0) 2025.03.20
[PS] Leet | 53. 최댓값을 가지는 하위 배열 - 덧셈  (0) 2025.03.19
[PS] Leet | 238. 자신을 제외한 곱  (0) 2025.03.18
'CS/PS' 카테고리의 다른 글
  • [PS] Leet | 33. 정렬된 회전 배열에서의 탐색
  • [PS] Leet | 153. 정렬된 회전배열에서의 최소값
  • [PS] Leet | 53. 최댓값을 가지는 하위 배열 - 덧셈
  • [PS] Leet | 238. 자신을 제외한 곱
Rayi
Rayi
  • Rayi
    아카이브
    Rayi
  • 전체
    오늘
    어제
    • 분류 전체보기 (262)
      • CS (40)
        • ML (3)
        • CV (2)
        • PS (34)
      • Reveiw (17)
        • Paper (17)
        • Github (0)
      • Pytorch (5)
      • Language (58)
        • Python (7)
        • JavaScript (32)
        • TypeScript (16)
        • C++ (3)
      • IDE (12)
      • Git (13)
      • Frontend (71)
        • React (8)
        • SolidJS (20)
        • CSS (12)
      • UI (3)
      • Backend (15)
        • DB (17)
        • Node.js (11)
  • 블로그 메뉴

    • 홈
    • 태그
    • 방명록
  • 링크

  • 공지사항

  • 인기 글

  • 태그

    CS
    ML
    DB
    postgresql
    ts
    deploy
    react
    frontend
    CSS
    mongo
    Express
    js
    vscode
    SOLID
    html
    UI
    PyTorch
    figma
    C++
    CV
    Git
    Three
    GAN
    ps
    python
    API
    review
    PRISMA
    nodejs
    backend
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.5
Rayi
[PS] Leet | 152. 최댓값을 가지는 하위 배열 - 곱셈
상단으로

티스토리툴바