Skip to content

Commit 32b261f

Browse files
committed
feat: add solution for maximum product subarray
1 parent b4269cb commit 32b261f

File tree

1 file changed

+21
-0
lines changed

1 file changed

+21
-0
lines changed
+21
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
#![allow(dead_code)]
2+
pub fn max_product(nums: Vec<i32>) -> i32 {
3+
let mut res = *nums.iter().max().unwrap();
4+
let (mut cur_min, mut cur_max) = (1, 1);
5+
6+
for &n in nums.iter() {
7+
let tmp = cur_max * n;
8+
cur_max = std::cmp::max(std::cmp::max(n * cur_max, n * cur_min), n);
9+
cur_min = std::cmp::min(std::cmp::min(tmp, n * cur_min), n);
10+
res = std::cmp::max(std::cmp::max(res, cur_max), cur_min);
11+
}
12+
13+
res
14+
}
15+
16+
#[test]
17+
fn test_max_product() {
18+
assert_eq!(max_product(vec![2, 3, -2, 4]), 6);
19+
assert_eq!(max_product(vec![-2, 0, -1]), 0);
20+
assert_eq!(max_product(vec![-2]), -2);
21+
}

0 commit comments

Comments
 (0)