LeetCode 152. Maximum Product Subarray (最大乘积子数组)

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.


题目标签:Array, Dynamic Programming

  题目给了我们一个nums array,让我们从中找到一个subarray, 它的乘积是最大的,返回乘积值。

  这道题目的难点在于,有0 和有 负数, 遇到0的话,就等于断点了,要重新开始记录新一段的subarray。遇到负数的话,如果是偶数的负数,那么依然可以保留,如果不是,那么也要重新开始记录。所以这道题目我们需要三个变量,来不断更新我们的subarray 的乘积。

  遍历nums array, max - 记录最大的subarray 乘积 从0 到 i。

           min  - 记录最小的subarray 乘积 从0 到 i,这里是需要到i, 在 i 前面的任何小段都不需要,为什么要记录最小的呢,因为有负数,要把最小的负值记录下来,当遇到新的负数,在可以配对成偶数的负数的情况下,把负数也利用进去。

           maxAns - 记录array 中 任意的最大乘积的 subarray 的值。

Java Solution:

Runtime beats 42.46% 

完成日期:08/28/2017

关键词:Array, Dynamic Programming

关键点:保持记录从0 到 i 的最大和最小subarray 的乘积值

 1 class Solution 
 2 {
 3     public int maxProduct(int[] nums) 
 4     {
 5         if(nums.length == 0)
 6             return 0;
 7         
 8         // save first number into max, min & maxAns
 9         int max = nums[0];
10         int min = nums[0];
11         int maxAns = nums[0];
12         
13         /* iterate rest number
14         * for each number, remember the max and min value for the previous product (0 ~ i)
15         */
16         for(int i=1; i<nums.length; i++)
17         {
18             int tmp_max = max;
19             int tmp_min = min;
20             
21             // remember the max product subarray from 0 to i
22             max = Math.max(Math.max(nums[i], tmp_max * nums[i]), tmp_min * nums[i]);
23             /* remember the min product subarray from 0 to i 
24             * min product subarray can only be from somewhere to i NOT somewhere to j that is before i
25             * because each time max use min and if min is not consecutive to current i, it is meaningless
26             */
27             min = Math.min(Math.min(nums[i], tmp_max * nums[i]), tmp_min * nums[i]);
28             
29             // update the maxAns
30             maxAns = Math.max(max, maxAns);
31         }
32         
33         return maxAns;
34     }
35 }

参考资料:

http://www.cnblogs.com/grandyang/p/4028713.html

LeetCode 算法题目列表 - LeetCode Algorithms Questions List

原文地址:https://www.cnblogs.com/jimmycheng/p/7447445.html