LeetCode: Maximum Product Subarray 解题报告

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

 

SOLUTION 1

使用DP来做:

因为有正负值好几种情况。所以我们计算当前节点最大值,最小值时,应该考虑前一位置的最大值,最大值几种情况。(例如:如果当前为-2, 前一个位置最小值为-6,最大值为8,那么当前最大值应该是-2*-6 = 12)

对于以index位置结尾的连续子串来说,计算最大,最小值可以三种选择:

1. 当前值* 前一位置的最大值。

2. 当前值* 前一位置的最小值。

3. 丢弃前一伴置的所有的值

我们对这三项取最大值,最小值,就可以得到当前的最大乘积,最小乘积。

 1 package Algorithms.array;

 2 

 3 public class MaxProduct {

 4     public static int maxProduct(int[] A) {

 5         if (A == null || A.length == 0) {

 6             return 0;

 7         }

 8         

 9         // record the max value in the last node.

10         int DMax = A[0];

11         

12         // record the min value in the last node.

13         int DMin = A[0];

14         

15         // This is very important, should recode the A[0] as the initial value.

16         int max = A[0];

17         

18         for (int i = 1; i < A.length; i++) {

19             int n1 = DMax * A[i];

20             int n2 = DMin * A[i];

21             

22             // we can select the former nodes, or just discade them.

23             DMax = Math.max(A[i], Math.max(n1, n2));

24             max = Math.max(max, DMax);

25             

26             // we can select the former nodes, or just discade them.

27             DMin = Math.min(A[i], Math.min(n1, n2));

28         }

29         

30         return max;

31     }

32     

33     /*

34      * 作法是找到连续的正数,不断相乘即可。

35      * */

36     public static void main(String[] strs) {

37         int[] A = {2, 3, -2, 4};

38         

39         System.out.println(maxProduct(A));

40     }

41 }
View Code

2014.12.20  Redo

 1 public class Solution {

 2     public int maxProduct(int[] A) {

 3         if (A == null || A.length == 0) {

 4             return 0;

 5         }

 6         

 7         int max = 1;

 8         int min = 1;

 9         

10         int ret = Integer.MIN_VALUE;

11         for (int i = 0; i < A.length; i++) {

12             int n1 = max * A[i];

13             int n2 = min * A[i];

14             

15             max = Math.max(A[i], Math.max(n1, n2));

16             min = Math.min(A[i], Math.min(n1, n2));

17             

18             ret = Math.max(max, ret);

19         }

20         

21         return ret;

22     }

23 }
View Code

GITHUB:

https://github.com/yuzhangcmu/LeetCode_algorithm/blob/master/array/MaxProduct.java

你可能感兴趣的:(LeetCode)