Skip to content

Commit 41caddb

Browse files
committed
solve #152
1 parent af729c0 commit 41caddb

File tree

2 files changed

+76
-0
lines changed

2 files changed

+76
-0
lines changed

src/lib.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -146,3 +146,4 @@ mod n0148_sort_list;
146146
mod n0149_max_points_on_a_line;
147147
mod n0150_evaluate_reverse_polish_notation;
148148
mod n0151_reverse_words_in_a_string;
149+
mod n0152_maximum_product_subarray;

src/n0152_maximum_product_subarray.rs

Lines changed: 75 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,75 @@
1+
/**
2+
* [152] Maximum Product Subarray
3+
*
4+
* Given an integer array nums, find the contiguous subarray within an array (containing at least one number) which has the largest product.
5+
*
6+
* Example 1:
7+
*
8+
*
9+
* Input: [2,3,-2,4]
10+
* Output: 6
11+
* Explanation: [2,3] has the largest product 6.
12+
*
13+
*
14+
* Example 2:
15+
*
16+
*
17+
* Input: [-2,0,-1]
18+
* Output: 0
19+
* Explanation: The result cannot be 2, because [-2,-1] is not a subarray.
20+
*
21+
*/
22+
pub struct Solution {}
23+
24+
// submission codes start here
25+
26+
/*
27+
f[i], g[i] means the max positive value and max negative value for the sub-seq end with index i
28+
29+
then we have:
30+
31+
f[i], g[i] = if nums[i] == 0 {
32+
0, 0
33+
} else if nums[i] > 0 {
34+
f[i-1] * nums[i], g[i-1] * nums[i]
35+
} else if nums[i] < 0 {
36+
g[i-1] * nums[i], f[i-1] * nums[i]
37+
}
38+
*/
39+
40+
impl Solution {
41+
pub fn max_product(nums: Vec<i32>) -> i32 {
42+
let mut max = nums[0];
43+
let mut neg_max = 0;
44+
let mut pos_max = 0;
45+
for num in nums.into_iter() {
46+
if num == 0 {
47+
neg_max = 0; pos_max = 0;
48+
max = i32::max(max, 0);
49+
} else if num > 0 {
50+
pos_max = i32::max(pos_max * num, num); neg_max = neg_max * num;
51+
} else {
52+
let pos_pre = pos_max;
53+
pos_max = neg_max * num; neg_max = i32::min(pos_pre * num, num);
54+
}
55+
if pos_max != 0 {
56+
max = i32::max(max, pos_max);
57+
}
58+
}
59+
max
60+
}
61+
}
62+
63+
// submission codes end
64+
65+
#[cfg(test)]
66+
mod tests {
67+
use super::*;
68+
69+
#[test]
70+
fn test_152() {
71+
assert_eq!(Solution::max_product(vec![2,3,-2,4]), 6);
72+
assert_eq!(Solution::max_product(vec![-2,0,-1]), 0);
73+
assert_eq!(Solution::max_product(vec![-4,-3,-2]), 12);
74+
}
75+
}

0 commit comments

Comments
 (0)