Guest User

Stock prices problem

a guest
Feb 16th, 2012
122
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Groovy 0.95 KB | None | 0 0
  1. prices1 = [4, 6, 3, 4, 2, 10, 11, 9, 13, 7, 10, 4]
  2. prices2 = [4, 6, 3, 4, 102, 2, 10, 11, 9, 13, 7, 10, 4, 100]
  3. prices3 = [1, 4, 6, 3, 4, 102, 2, 10, 11, 9, 13, 7, 10, 4, 100]
  4. prices4 = [1, 1, 1, 1, 1, 1, 1]
  5. prices5 = [1, 1, 1, 2, 1, 1, 1]
  6. prices6 = [3, 1, 1, 1, 1, 1, 1, 1]
  7.  
  8.  
  9. findbest = {prices ->
  10.     def sell, profit, buy
  11.     //goal is to minimize buy and maximize sell
  12.    
  13.     // initialize
  14.     sell = 0
  15.     buy = Integer.MAX_VALUE
  16.     profit = 0
  17.    
  18.     // lets iterate and find maximum profit
  19.     prices.each {p->
  20.         buy = p < buy ? p : buy // see if we buy at a lower price
  21.         sell = (buy == p ? 0 : (sell < p ? p : sell)) // reset sell if it is lower buy. set sell if we get a better price
  22.         profit = (sell - buy) > profit ? (sell - buy) : profit // check to see if we can maximize profit
  23.     }
  24.     println profit
  25. }
  26.  
  27. pset = [prices1, prices2, prices3, prices4, prices5, prices6]
  28. pset.each {ps ->
  29.     findbest(ps)
  30. }
Advertisement
Add Comment
Please, Sign In to add comment