[leetcode]152. Maximum Product Subarray最大乘积子数组

Posted 程序媛詹妮弗

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[leetcode]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.

 

题意:

求最大乘积子数组

 

思路:

负负得正,正负得负。                                       

                            /  最大乘积子数组  * nums[i]

所以nums[i] 结尾的最大乘积子数组取决于nums[i-1]结尾的 

                                                        最小乘积子数组  * nums[i]

 

 

代码:

 1 class Solution {
 2      public int maxProduct(int[] nums) {
 3         int[] max = new int[nums.length];
 4         int[] min = new int[nums.length];
 5         max[0] = nums[0];
 6         min[0] = nums[0];
 7         int result = nums[0];
 8         for(int i = 1; i < nums.length; i++){
 9             max[i] = Math.max(Math.max(max[i-1] * nums[i] , min[i-1]*nums[i]), nums[i]);
10             min[i] = Math.min(Math.min(max[i-1] * nums[i] , min[i-1]*nums[i]), nums[i]);
11             result = Math.max(result, max[i]);
12         }
13         return result;
14     }
15 }

 

以上是关于[leetcode]152. Maximum Product Subarray最大乘积子数组的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode152. Maximum Product Subarray

[leetcode-152-Maximum Product Subarray]

leetcode152. Maximum Product Subarray

LeetCode-152-Maximum Product Subarray

[动态规划] leetcode 152 Maximum Product Subarray

leetcode 152. Maximum Product Subarray --------- java