Tuesday, January 27, 2015

Simple Best Time Stock

Question: Given an array, find the maximum difference between two array elements given the second element comes after the first.

Idea: Use a variable to remember the minimum showed up before.

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

Code:
 public class maxSub {  
      public maxSub()  
      {  
           int[] input1={1,2,3,4};  
           int[] input2={-5,1,6,17};  
           int[] input3={90,12,4,-11};  
           System.out.println(maxSubInArray(input1));  
           System.out.println(maxSubInArray(input2));  
           System.out.println(maxSubInArray(input3));  
      }  
      public int maxSubInArray(int[] A)  
      {  
           if(A.length<=1)  
                return 0;  
           int minNow=A[0];  
           int maxSubNow=Integer.MIN_VALUE;  
           for(int i=1;i<A.length;i++)  
           {  
                maxSubNow=Math.max(A[i]-minNow, maxSubNow);  
                minNow=Math.min(minNow,A[i]);  
           }  
           return maxSubNow;  
      }  
 }  

No comments:

Post a Comment