Wednesday, December 31, 2014

Maximum Product Subarray (HashMap Array)

Question: 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.

Idea: Dynamic Programming. We need to go through all the local maximals to get the global maximum (the result). Since the array may start with either positive and negative numbers, there are many cases of local maximals, e.g. previous maximal >0,  array[i]<0 or previous maximal <0, array[i]<0. It will be too complex to list all the cases.
However, the local maximal at position i must be among three numbers: previous maximal * array[i], previous minimal*array[i] and array[i] itself, e.g. [-1, 2] when i==1. So we just need to cache the previous maximal and previous minimal and use a function maxOfThree(a,b,c) to deliver the values to next calculation.

Time: O(n) Space: O(1)

Code:  
 public class Solution {  
   public int maxOfThree(int a,int b,int c)  
   {  
     return Math.max(a,Math.max(b,c));  
   }  
   public int minOfThree(int a,int b,int c)  
   {  
     return Math.min(a,Math.min(b,c));  
   }  
   public int maxProduct(int[] A) {  
     if(A.length==1)  
       return A[0];  
     int maxPre=A[0];  
     int minPre=A[0];  
     int maxSoFar=A[0];  
     for(int i=1;i<A.length;i++)  
     {  
       int maxHere=maxOfThree(maxPre*A[i],minPre*A[i],A[i]);  
       int minHere=minOfThree(maxPre*A[i],minPre*A[i],A[i]);  
       maxSoFar=Math.max(maxHere,maxSoFar);  
       maxPre=maxHere;  
       minPre=minHere;  
     }  
     return maxSoFar;  
   }  
 }  

No comments:

Post a Comment