Skip to content

Instantly share code, notes, and snippets.

@bryangarza
Last active November 8, 2015 03:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bryangarza/df981c2dc2e614a51727 to your computer and use it in GitHub Desktop.
Save bryangarza/df981c2dc2e614a51727 to your computer and use it in GitHub Desktop.
import Control.Monad (liftM2)
import Data.List (tails)
import Data.Maybe (fromMaybe, mapMaybe)
import Safe.Foldable (maximumMay)
prices = [10, 30, 42, 15, 20, 50, 10, 25]
profit :: [Integer] -> Integer
profit = fromMaybe 0 . maximumMay . mapMaybe (uncurry (liftM2 (-))) . large
large :: Ord a => [a] -> [(Maybe a, Maybe a)]
large xs = map (\(ys,x) -> (maxfil x ys, Just x)) (zip (tails xs) xs)
where maxfil x ys = maximumMay (filter (>x) ys)
-- Given predicted stock prices for next n days for a stock e.g : 10, 30, 42, 15,
-- 20, 50, 10, 25 find the maximum profit that can be made with a single buy-sell
-- transaction. If no profit can be made return 0. In the example buying at 10 and
-- selling at 50 gives maximum profit.
-- profit prices == 40
-- profit (tail prices) == 35
-- profit [30,21,34,52,67,32,45,67,25,78,31,54,64,22] == 57
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment