LeetCode 152 Maximum Product Subarray (思维)

来源:互联网 发布:蒙牛微销售打卡软件 编辑:程序博客网 时间:2024/05/20 14:26

Find the contiguous subarray within an array (containing at least one number) which has the largest product.

For example, given the array [2,3,-2,4],
the contiguous subarray [2,3] has the largest product = 6.

题目链接:https://leetcode.com/problems/maximum-product-subarray/

题目分析:维护当前的最大和最小,若当前为负数,最小值乘完会变大

public class Solution {    public int maxProduct(int[] nums) {        int n = nums.length;        int ma = nums[0], mi = nums[0], ans = nums[0];        for (int i = 1; i < n; i ++) {            if (nums[i] < 0) {                int tmp = mi;                mi = ma;                ma = tmp;            }            ma = Math.max(nums[i], ma * nums[i]);            mi = Math.min(nums[i], mi * nums[i]);            ans = Math.max(ans, ma);        }        return ans;    }}


原创粉丝点击