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 ์ ์ ์ฅํ๋ค.
'Algorithm > Leetcode' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
๋งค์ผ LeetCode ํ๊ธฐ | Maximum Subarray (0) | 2024.08.21 |
---|---|
๋งค์ผ LeetCode ํ๊ธฐ | 3Sums (0) | 2024.08.21 |
๋งค์ผ LeetCode ํ๊ธฐ | Number of 1 bits (0) | 2024.08.19 |
๋งค์ผ LeetCode ํ๊ธฐ | Sum of Two Integers (0) | 2024.08.18 |
๋งค์ผ LeetCode ํ๊ธฐ | Product of Array Except Self (0) | 2024.08.15 |