Maximum Product Subarray

2025. 1. 8. 00:34·PS/LeetCode
반응형

문제

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

입력

1 <= nums.length <= 2 * 10^4
-10 <= nums[i] <= 10

결과

ans: Int = 곱 부분 배열의 최댓값

해석

이전 maxSubarray는 단순 합이라, 흐름이 하나였지만

곱은 말 그대로 음수와 양수에 따른 흐름이 2개이므로 변수가 하나 더 필요했다.

그래서 음수를 고려한 최대 음수 변수와, 최대 양수 변수를 계속 가져가며 반복마다 갱신한다.

코드

class Solution {
    func maxProduct(_ nums: [Int]) -> Int {
        let n = nums.count

        if n == 1 {
            return nums[0]
        }

        var minProduct = nums[0] // 음수 최댓값
        var maxProduct = nums[0] // 양수 최댓값
        var ans = nums[0]

        for i in 1..<n {
            let now = nums[i]
            let candidate = [now, minProduct * now, maxProduct * now]
            minProduct = candidate.min()!
            maxProduct = candidate.max()!
            ans = max(ans, maxProduct)
        }
    
        return ans
    }
}

 

반응형

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

Search in Rotated Sorted Array  (0) 2025.01.09
Find Minimum in Rotated Sorted Array  (0) 2025.01.08
Maximum Subarray  (1) 2025.01.05
Product of Array Except Self  (0) 2025.01.05
Best Time to Buy and Sell Stock  (0) 2025.01.05
'PS/LeetCode' 카테고리의 다른 글
  • Search in Rotated Sorted Array
  • Find Minimum in Rotated Sorted Array
  • Maximum Subarray
  • Product of Array Except Self
Hamp
Hamp
남들에게 보여주기 부끄러운 잡다한 글을 적어 나가는 자칭 기술 블로그입니다.
  • Hamp
    Hamp의 분리수거함
    Hamp
  • 전체
    오늘
    어제
    • 분류 전체보기 (329) N
      • CS (30)
        • 객체지향 (2)
        • Network (7)
        • OS (6)
        • 자료구조 (1)
        • LiveStreaming (3)
        • 이미지 (1)
        • 잡다한 질문 정리 (0)
        • Hardware (2)
        • 이론 (6)
        • 컴퓨터 그래픽스 (0)
      • Firebase (3)
      • Programing Langauge (41)
        • swift (34)
        • python (6)
        • Kotlin (1)
      • iOS (134)
        • UIKit (37)
        • Combine (1)
        • SwiftUI (34)
        • Framework (7)
        • Swift Concurrency (22)
        • Tuist (6)
        • Setting (11)
        • Modularization (1)
        • Instruments (6)
      • PS (59)
        • 프로그래머스 (24)
        • 백준 (13)
        • LeetCode (19)
        • 알고리즘 (3)
      • Git (18)
        • 명령어 (4)
        • 이론 (2)
        • hooks (1)
        • config (2)
        • action (7)
      • Shell Script (2)
      • Linux (6)
        • 명령어 (5)
      • Spring (21)
        • 어노테이션 (6)
        • 튜토리얼 (14)
      • CI-CD (4)
      • Android (0)
        • Jetpack Compose (0)
      • AI (11) N
        • 이론 (10) N
        • MCP (1)
        • LangGraph (0)
  • 블로그 메뉴

    • 홈
    • 태그
  • 링크

  • 공지사항

  • 인기 글

  • 태그

    protocol
    IOS
    dp
    Swift
    dispatch
    Spring
    UIKit
    dfs
    SwiftUI
    concurrency
    백준
    투포인터
    boostcamp
    프로그래머스
    AVFoundation
    CS
    GIT
    Tuist
    property
    lifecycle
  • 최근 댓글

  • 최근 글

  • 반응형
  • hELLO· Designed By정상우.v4.10.0
Hamp
Maximum Product Subarray
상단으로

티스토리툴바