Skip to content

Commit 166f370

Browse files
committed
feat: Add solution for LeetCode problem 152
1 parent 63ddb7c commit 166f370

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
//
2+
// 152. Maximum Product Subarray
3+
// https://leetcode.com/problems/maximum-product-subarray/description/
4+
// Dale-Study
5+
//
6+
// Created by WhiteHyun on 2024/07/14.
7+
//
8+
9+
class Solution {
10+
func maxProduct(_ nums: [Int]) -> Int {
11+
var maxNumber = nums[0]
12+
var minNumber = nums[0]
13+
var answer = nums[0]
14+
// Problem 190 / 191 방어 코드
15+
let negativeCount = nums.filter { $0 < 0 }.count
16+
17+
18+
for index in 1 ..< nums.count {
19+
let current = nums[index]
20+
21+
let tempMin = minNumber
22+
let tempMax = maxNumber
23+
24+
maxNumber = max(current, tempMin * current, tempMax * current)
25+
if negativeCount > 1 {
26+
minNumber = min(current, tempMin * current, tempMax * current)
27+
} else {
28+
minNumber = 0
29+
}
30+
if answer < maxNumber {
31+
answer = maxNumber
32+
}
33+
}
34+
35+
return answer
36+
}
37+
38+
}

0 commit comments

Comments
 (0)