๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ

Algorithm/Leetcode

๋งค์ผ LeetCode ํ’€๊ธฐ | 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.
 
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.
 
Constraints:
1 <= nums.length <= 2 * 104-10 <= nums[i] <= 10The product of any subarray of nums is guaranteed to fit in a 32-bit integer.

 

์ €๋ฒˆ์— ํ‘ผ ๋ถ€๋ถ„๋ฐฐ์—ด์ด๋ž‘ ๊ฐ™์€ ์›๋ฆฌ๋ผ์„œ, ์œ ๋ ˆ์นด ํ•˜๊ณ  ํ’€์—ˆ๋Š”๋ฐ.. ์Œ์ˆ˜์˜ ๊ฒฝ์šฐ๋ฅผ ๊ณ ๋ คํ•˜์ง€ ์•Š์•„์„œ ํ‹€๋ ธ๋˜ ๋ฌธ์ œ. ์Œ์ˆ˜๊นŒ์ง€ ๊ณ ๋ คํ• ๋ ค๋‹ˆ ์กฐ๊ธˆ ์–ด๋ ต๊ฒŒ ๋А๊ปด์ง€๊ธฐ๋„ ํ–ˆ๋‹ค. 

 

๊ธฐ์กด ์ฝ”๋“œ 

class Solution {
    func maxProduct(_ nums: [Int]) -> Int {
        var current = nums[0]
        var maxTotal = nums[0]

        for i in 1..<nums.count {
            current = max(nums[i], current * nums[i])
            maxTotal = max(maxTotal, current)
        }

        return maxTotal
    }
}

 

๋ฐฐ์šด ์ฝ”๋“œ 

class Solution {
    func maxProduct(_ nums: [Int]) -> Int {
        var maxProduct = nums[0]
        var minProduct = nums[0]
        var maxTotal = nums[0] 

        for i in 1..<nums.count {
            let temp = maxProduct

            maxProduct = max(nums[i], max(maxProduct * nums[i], minProduct * nums[i]))
            minProduct = min(nums[i], min(temp * nums[i], minProduct * nums[i]))
            
            maxTotal = max(maxTotal, maxProduct)
        }

        return maxTotal
    }
}

 

์ ‘๊ทผ ๋ฐฉ์‹ 
1. ์ง€๊ธˆ๊นŒ์ง€ ๊ณ„์‚ฐ์˜ ๊ฐ€์žฅ ํฐ ๊ฐ’์„ ๋‹ด๋Š” maxProduct, ์ง€๊ธˆ๊นŒ์ง€ ๊ณ„์‚ฐ์˜ ๊ฐ€์žฅ ์ž‘์€ ๊ฐ’์„ ๋‹ด๋Š” minProduct, ์ตœ์ข… ์ตœ๋Œ€ ๊ฐ’์„ ๊ตฌํ•˜๋Š” maxTotal ๋ณ€์ˆ˜๋ฅผ ์„ ์–ธํ•œ๋‹ค. 
2. ๋ฐ˜๋ณต๋ฌธ์„ ๋ˆ๋‹ค. 
2-1. maxProduct : (์ง€๊ธˆ๊นŒ์ง€ ๊ณ„์‚ฐ์˜ ์ตœ๋Œ€๊ฐ’ * ํ˜„์žฌ ์›์†Œ) & (์ง€๊ธˆ๊นŒ์ง€ ๊ณ„์‚ฐ์˜ ์ตœ์†Œ๊ฐ’ * ํ˜„์žฌ ์›์†Œ) ์ค‘ ์ตœ๋Œ€๊ฐ’์„ ํ˜„์žฌ ์›์†Œ์™€ ๋น„๊ตํ•ด ๋” ํฐ ๊ฐ’์„ ์ €์žฅํ•œ๋‹ค. 
2-2. minProduct: (์ง€๊ธˆ๊นŒ์ง€ ๊ณ„์‚ฐ์˜ ์ตœ๋Œ€๊ฐ’ * ํ˜„์žฌ ์›์†Œ) & (์ง€๊ธˆ๊นŒ์ง€ ๊ณ„์‚ฐ์˜ ์ตœ์†Œ๊ฐ’ * ํ˜„์žฌ ์›์†Œ) ์ค‘ ์ตœ์†Œ๊ฐ’์„ ํ˜„์žฌ์›์†Œ์™€ ๋น„๊ตํ•ด ๋” ์ž‘์€ ๊ฐ’์„ ์ €์žฅํ•œ๋‹ค. 
2-3. maxProduct ์™€ minProduct ์ค‘ ์ตœ๋Œ€ ๊ฐ’์„ ์ตœ์ข… maxTotal ์— ์ €์žฅํ•œ๋‹ค.