Leetcode152——Maximum Product Subarray

来源:互联网 发布:python 2.7.x下载官网 编辑:程序博客网 时间:2024/06/06 01:06

文章作者:Tyan
博客:noahsnail.com  |  CSDN  |  简书

1. 问题描述

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.

2. 求解

这个题跟Leetcode 53——Maximum Subarray类似,可以用三重循环,两种循环解决。但最好的还是用动态规划解决,找出状态转移方程最关键。由于乘积可能为负数,负负得正,因此第i-1次的乘积最大值(maxValuePre)与最小值(minValuePre)都需要保留。当然也可以定义最大值最小值数组来保存第i次乘积的最大值(maxValue)与最小值(minValue)。与Maximum Subarray相比,最大值为maxValue = max(minValuePre * nums[i], maxValuePre * nums[i], nums[i]),最小值同样如此。

没有定义最大值数组与最小值数组

public class Solution {    public int maxProduct(int[] nums) {        int n = nums.length;        int maxValue = nums[0];        int minValue = nums[0];        int result = nums[0];        int maxValuePre = nums[0], minValuePre = nums[0];        for(int i = 1; i < n; i++) {            maxValue = Math.max(minValuePre * nums[i], Math.max(maxValuePre * nums[i], nums[i]));            minValue = Math.min(minValuePre * nums[i], Math.min(maxValuePre * nums[i], nums[i]));            if(maxValue > result) {                result = maxValue;            }            maxValuePre = maxValue;            minValuePre = minValue;        }        return result;    }}

定义最大值数组与最小值数组

public class Solution {    public int maxProduct(int[] nums) {        int n = nums.length;        int maxValue[] = new int[nums.length];        int minValue[] = new int[nums.length];        maxValue[0] = nums[0];        minValue[0] = nums[0];        int result = nums[0];        for(int i = 1; i < n; i++) {            maxValue[i] = Math.max(minValue[i - 1] * nums[i], Math.max(maxValue[i - 1] * nums[i], nums[i]));            minValue[i] = Math.min(minValue[i - 1] * nums[i], Math.min(maxValue[i - 1] * nums[i], nums[i]));            if(maxValue[i] > result) {                result = maxValue[i];            }        }        return result;    }}
0 0
原创粉丝点击