Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- prices1 = [4, 6, 3, 4, 2, 10, 11, 9, 13, 7, 10, 4]
- prices2 = [4, 6, 3, 4, 102, 2, 10, 11, 9, 13, 7, 10, 4, 100]
- prices3 = [1, 4, 6, 3, 4, 102, 2, 10, 11, 9, 13, 7, 10, 4, 100]
- prices4 = [1, 1, 1, 1, 1, 1, 1]
- prices5 = [1, 1, 1, 2, 1, 1, 1]
- prices6 = [3, 1, 1, 1, 1, 1, 1, 1]
- findbest = {prices ->
- def sell, profit, buy
- //goal is to minimize buy and maximize sell
- // initialize
- sell = 0
- buy = Integer.MAX_VALUE
- profit = 0
- // lets iterate and find maximum profit
- prices.each {p->
- buy = p < buy ? p : buy // see if we buy at a lower price
- sell = (buy == p ? 0 : (sell < p ? p : sell)) // reset sell if it is lower buy. set sell if we get a better price
- profit = (sell - buy) > profit ? (sell - buy) : profit // check to see if we can maximize profit
- }
- println profit
- }
- pset = [prices1, prices2, prices3, prices4, prices5, prices6]
- pset.each {ps ->
- findbest(ps)
- }
Advertisement
Add Comment
Please, Sign In to add comment