Leetcode 152. Maximum Product Subarray

来源:互联网 发布:上海火速网络 编辑:程序博客网 时间:2024/06/13 12:41
/** * dynamic programming approach * similar with maximum sum subarray, there are scenariors, * i. targert subarray starts from n, then f(n) = nums[n] * ii. if nums[0] > 0, f(n-1) > n, then f(n) = nums[n]*f(n-1) * iii. if nums[0] <= 0, f(n-1) < n, then f(n) = nums[n]*f(n-1) * we need another array to store non-positive results to handle the case when nums[i] is non-positive */ public class Solution {    public int maxProduct(int[] nums) {        int[] max = new int[nums.length];        int[] min = new int[nums.length];             max[0] = min[0] = nums[0];        int result = nums[0];             for(int i=1; i<nums.length; i++){            if(nums[i]>0){                max[i]=Math.max(nums[i], max[i-1]*nums[i]);                min[i]=Math.min(nums[i], min[i-1]*nums[i]);            }else{                max[i]=Math.max(nums[i], min[i-1]*nums[i]);                min[i]=Math.min(nums[i], max[i-1]*nums[i]);            }                 result = Math.max(result, max[i]);        }             return result;    }}

0 0