Skip to content

Commit 0d926ff

Browse files
committed
Added Maximum Product Subarray
1 parent 5c3ad7c commit 0d926ff

File tree

2 files changed

+71
-5
lines changed

2 files changed

+71
-5
lines changed

Diff for: src/lib.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -145,7 +145,7 @@ pub mod sort_list; // 148
145145

146146
pub mod evaluate_reverse_polish_notation; // 150 ✓
147147
pub mod reverse_words_in_a_string; // 151 ✓
148-
pub mod maximum_product_subarray; // 152
148+
pub mod maximum_product_subarray; // 152
149149
pub mod find_minimum_in_rotated_sorted_array; // 153 ✓
150150

151151
pub mod min_stack; // 155

Diff for: src/maximum_product_subarray.rs

+70-4
Original file line numberDiff line numberDiff line change
@@ -6,8 +6,50 @@ struct Solution;
66

77
impl Solution {
88

9-
pub fn max_product(_nums: Vec<i32>) -> i32 {
10-
0
9+
pub fn max_product(nums: Vec<i32>) -> i32 {
10+
let mut result = i32::MIN;
11+
12+
let mut negative_result = i32::MAX;
13+
let mut positive_result = i32::MIN;
14+
15+
for num in nums {
16+
if num == 0 {
17+
result = result.max(0);
18+
negative_result = i32::MAX;
19+
positive_result = i32::MIN;
20+
} else if num > 0 {
21+
if negative_result != i32::MAX {
22+
negative_result *= num;
23+
}
24+
if positive_result == i32::MIN {
25+
positive_result = num;
26+
} else {
27+
positive_result *= num;
28+
}
29+
result = result.max(positive_result);
30+
} else { // num < 0
31+
if negative_result == i32::MAX {
32+
if positive_result != i32::MIN {
33+
negative_result = positive_result * num;
34+
positive_result = i32::MIN;
35+
} else {
36+
negative_result = num;
37+
}
38+
result = result.max(num);
39+
} else {
40+
let temp = negative_result * num;
41+
negative_result = if positive_result != i32::MIN {
42+
num * positive_result
43+
} else {
44+
num
45+
};
46+
positive_result = temp;
47+
result = result.max(positive_result);
48+
}
49+
}
50+
}
51+
52+
result
1153
}
1254

1355
}
@@ -16,15 +58,39 @@ impl Solution {
1658
mod tests {
1759
use super::Solution;
1860

19-
#[ignore]
2061
#[test]
2162
fn example_1() {
2263
let nums = vec![2,3,-2,4];
2364
let result = Solution::max_product(nums);
2465
assert_eq!(result, 6);
2566
}
2667

68+
#[test]
69+
fn example_2() {
70+
let nums = vec![-2,0,-1];
71+
let result = Solution::max_product(nums);
72+
assert_eq!(result, 0);
73+
}
2774

28-
// TODO: Add More Tests
75+
#[test]
76+
fn example_3() {
77+
let nums = vec![-2];
78+
let result = Solution::max_product(nums);
79+
assert_eq!(result, -2);
80+
}
81+
82+
#[test]
83+
fn example_4() {
84+
let nums = vec![7,-2,-4];
85+
let result = Solution::max_product(nums);
86+
assert_eq!(result, 56);
87+
}
88+
89+
#[test]
90+
fn example_5() {
91+
let nums = vec![-1,-2,-9,-6];
92+
let result = Solution::max_product(nums);
93+
assert_eq!(result, 108);
94+
}
2995

3096
}

0 commit comments

Comments
 (0)