152. Maximum Product Subarray

Given an integer array nums, find the contiguous subarray within an array (containing at least one number) which has the largest product.

Example 1:

Input: [2,3,-2,4]
Output: 6
Explanation: [2,3] has the largest product 6.

Example 2:

Input: [-2,0,-1]
Output: 0
Explanation: The result cannot be 2, because [-2,-1] is not a subarray.

Rust Solution

struct Solution;

use std::i32;
use std::mem::swap;

impl Solution {
    fn max_product(nums: Vec<i32>) -> i32 {
        let mut res = nums[0];
        let mut min = res;
        let mut max = res;
        let n = nums.len();
        for i in 1..n {
            let x = nums[i];
            if x < 0 {
                swap(&mut min, &mut max);
            }
            max = i32::max(x, max * x);
            min = i32::min(x, min * x);
            res = i32::max(res, max);
        }
        res
    }
}

#[test]
fn test() {
    let nums = vec![2, 3, -2, 4];
    assert_eq!(Solution::max_product(nums), 6);
    let nums = vec![-2, 0, -1];
    assert_eq!(Solution::max_product(nums), 0);
}

Having problems with this solution? Click here to submit an issue on github.