rustgym/leetcode/
_152_maximum_product_subarray.rs1struct Solution;
2
3use std::i32;
4use std::mem::swap;
5
6impl Solution {
7 fn max_product(nums: Vec<i32>) -> i32 {
8 let mut res = nums[0];
9 let mut min = res;
10 let mut max = res;
11 let n = nums.len();
12 for i in 1..n {
13 let x = nums[i];
14 if x < 0 {
15 swap(&mut min, &mut max);
16 }
17 max = i32::max(x, max * x);
18 min = i32::min(x, min * x);
19 res = i32::max(res, max);
20 }
21 res
22 }
23}
24
25#[test]
26fn test() {
27 let nums = vec![2, 3, -2, 4];
28 assert_eq!(Solution::max_product(nums), 6);
29 let nums = vec![-2, 0, -1];
30 assert_eq!(Solution::max_product(nums), 0);
31}