Skip to content

Commit 96dedf8

Browse files
authored
maximum product subarray solution
1 parent 54aee8d commit 96dedf8

File tree

1 file changed

+26
-0
lines changed

1 file changed

+26
-0
lines changed
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
impl Solution {
2+
pub fn max_product(nums: Vec<i32>) -> i32 {
3+
let mut neg_abs_min = 1;
4+
let mut total = 1;
5+
let mut ans = *nums.first()
6+
.unwrap();
7+
for num in nums {
8+
if num == 0 {
9+
neg_abs_min = 1;
10+
total = 1;
11+
ans = ans.max(0);
12+
continue
13+
}
14+
total *= num;
15+
ans = ans.max(total);
16+
if total < 0 {
17+
if neg_abs_min == 1 {
18+
neg_abs_min = total;
19+
} else {
20+
ans = ans.max(total / neg_abs_min)
21+
}
22+
}
23+
}
24+
ans
25+
}
26+
}

0 commit comments

Comments
 (0)