[LeetCode] 152. Maximum Product Subarray - 파이썬(Python)

2022. 5. 13. 18:54·Solving Algorithm Problem/LeetCode

문제 링크 : https://leetcode.com/problems/maximum-product-subarray/

 

Maximum Product Subarray - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

유형 : 동적 계획법(Dynamic Programming)

문제 설명

정수 배열 nums가 주어질 때, 가장 큰 곱 값을 갖는 연속적인 하위 배열을 return 하는 문제이다. 이때, 하위 배열의 요소들은 연속되어야 한다. 예를 들어 num = [1,2,3] 일 때, 연속되지 않는 [1,3]은 하위 배열이 될 수 없다.

Example 1)
Input: nums = [2,3,-2,4]
Output: 6
Explanation: [2,3]이 최대곱을 가지는 하위 배열이다.
Example 2)
Input: nums = [-2,0,-1]
Output: 0

제한사항

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

문제 풀이

성공 코드

from typing import List

class Solution:
    def maxProduct(self, nums: List[int]) -> int:
        if len(nums) == 1:
            return nums[0]
        
        min_dp = [nums[0]]
        max_dp = [nums[0]]
        
        for idx in range(1,len(nums)):
            prev_idx = idx - 1
            
            num = nums[idx]
            cand0 = num
            cand1 = max_dp[prev_idx] * num
            cand2 = min_dp[prev_idx] * num
            
            max_val = max(cand0,cand1,cand2)
            min_val = min(cand0,cand1,cand2)
            
            max_dp.append(max_val)
            min_dp.append(min_val)
            
        max_product = max(max_dp)
        return max_product

시간 복잡도 : O(n)

n은 nums의 크기이다.

공간 복잡도 : O(n)

n은 nums의 크기이다.

 

저작자표시
'Solving Algorithm Problem/LeetCode' 카테고리의 다른 글
  • [LeetCode] 53. Maximum Subarray - 파이썬(Python)
  • [LeetCode] 91. Decode Ways - 파이썬(Python)
  • [LeetCode] 322. Coin Change - 파이썬(Python)
  • [LeetCode] 64. Minimum Path Sum - 파이썬(Python)
김행만
김행만
이모저모 다 적기
  • 김행만
    hyeinisfree
    김행만
  • 전체
    오늘
    어제
    • 분류 전체보기 (41)
      • AWS (0)
      • Network (6)
      • CICD (1)
      • Spring (0)
      • Ruby on Rails (0)
      • Java (12)
      • Python (1)
      • Computer Science (6)
        • Algorithm (2)
        • Data Structure (3)
        • Database (0)
        • Design Pattern (1)
      • Solving Algorithm Problem (12)
        • LeetCode (12)
        • Programmers (0)
      • 자격증 (1)
      • Tip (1)
      • Etc (1)
        • 도서, 강의 (1)
        • Talk (0)
  • 블로그 메뉴

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

    • GitHub
  • 공지사항

  • 인기 글

  • 태그

    Network
    Packet Tracer
    cisco packet tracer
    java 필수 문법
    java
    CISCO
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.3
김행만
[LeetCode] 152. Maximum Product Subarray - 파이썬(Python)
상단으로

티스토리툴바