Skip to content

Commit e13b122

Browse files
committed
Added solution of problem 152
1 parent 607cce8 commit e13b122

File tree

2 files changed

+33
-0
lines changed

2 files changed

+33
-0
lines changed

src/solutions/mod.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -87,6 +87,7 @@ pub mod s0147_insertion_sort_list;
8787
pub mod s0148_sort_list;
8888
pub mod s0150_evaluate_reverse_polish_notation;
8989
pub mod s0151_reverse_words_in_a_string;
90+
pub mod s0152_maximum_product_subarray;
9091
pub mod s0231_power_of_two;
9192
pub mod s0232_implement_queue_using_stacks;
9293
pub mod s0234_palindrome_linked_list;
Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
pub fn max_product(nums: Vec<i32>) -> i32 {
2+
let mut min_prod: i32 = nums[0];
3+
let mut max_prod: i32 = nums[0];
4+
let mut result: i32 = nums[0];
5+
6+
for (_, value) in nums.iter().enumerate().skip(1) {
7+
let test_max_prod: i32 = max_prod * *value;
8+
let test_min_prod: i32 = min_prod * *value;
9+
10+
max_prod = test_min_prod.max(test_max_prod).max(*value);
11+
min_prod = test_max_prod.min(test_min_prod).min(*value);
12+
13+
result = result.max(max_prod);
14+
}
15+
16+
result
17+
}
18+
19+
#[cfg(test)]
20+
mod test {
21+
use super::*;
22+
23+
#[test]
24+
fn test_case_1() {
25+
assert_eq!(max_product(vec![2, 3, -2, 4]), 6);
26+
}
27+
28+
#[test]
29+
fn test_case_2() {
30+
assert_eq!(max_product(vec![-2, 0, -1]), 0);
31+
}
32+
}

0 commit comments

Comments
 (0)