Last active
October 17, 2021 20:36
-
-
Save avestura/9d35de3bae51c89a75e8a19bad757400 to your computer and use it in GitHub Desktop.
F# Script to find min x and max y with condition index(y) > index(x) and maximum y-x
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
let findSpecialMinMax arr = | |
let rec f arr bestMin bestMax currentMin currentMax = | |
match arr with | |
| [] -> (bestMin, bestMax) | |
| cur::rest -> | |
match (bestMin, bestMax) with | |
| None, _ -> f rest (Some cur) None None None | |
| Some min, None -> | |
if cur > min then f rest (Some min) (Some cur) None None | |
else f rest (Some cur) None None None | |
| Some min, Some max -> | |
match currentMin, currentMax with | |
| None, _ -> | |
if cur < min then f rest bestMin bestMax (Some cur) None | |
else if cur >= max then f rest bestMin (Some cur) None None | |
else f rest bestMin bestMax None None | |
| Some cMin, None -> | |
if cur < cMin then f rest bestMin bestMax (Some cur) None | |
else | |
if cur - cMin > max - min then f rest currentMin (Some cur) None None | |
else f rest bestMin bestMax currentMin (Some cur) | |
| Some cMin, Some cMax -> | |
if cur < cMin then f rest bestMin bestMax (Some cur) None | |
else if cur >= cMax then | |
if cur - cMin > max - min then f rest currentMin (Some cur) None None | |
else f rest bestMin bestMax currentMin (Some cur) | |
else f rest bestMin bestMax currentMin currentMax | |
f arr None None None None | |
let test arr = findSpecialMinMax arr |> printfn "%A" | |
test [5; 8; 1; 3; 3] // (Some 5, Some 8) | |
test [4; 3; 2; 1; 0] // (Some 0, None) | |
test [1; 2; 3; 4; 5] // (Some 1, Some 5) | |
test [9; 7; 1; 12; 15; 8; 3] // (Some 1, Some 15) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment