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.

思路:利用动态规划思想,记录到每个数截止时的最大值和最小值,用来推导下一个数的最大值和最小值;

代码:

  1. int maxProduct(int A[], int n) {
  2. if(n==0) return 0;
  3. if(n==1) return A[0];
  4. int max_here_val = A[0];
  5. int min_here_val = A[0];
  6. int max_val = A[0];
  7. for(int i=1;i<n;i++) {
  8. int tmp = max_here_val;
  9. max_here_val = max(max(max_here_val * A[i],A[i]),min_here_val * A[i]); // the max value of current
  10. min_here_val = min(min(A[i],tmp * A[i]),min_here_val * A[i]); //the min value of current
  11. if(max_here_val > max_val) {
  12. max_val = max_here_val;
  13. }
  14. }
  15. return max_val;
  16. }
posted @ 2014-10-05 20:02  purejade  阅读(87)  评论(0)    收藏  举报