-
-
Save keturiosakys/ef0d54563dc1cc728c902f1ea7b875f1 to your computer and use it in GitHub Desktop.
Given an array where each element is the price of a given stock on that index's day, choose a single day to buy a stock and a different day (in the future/later in the array) to sell the stock to maximize your profit. Return the maximum profit that you can get from a given input. If you can't profit, return 0.
This file contains 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
open Base | |
open Stdio | |
let max_profit (indices : int list) = | |
let rec calculate_profit profit = function | |
| [] -> profit | |
| buy :: rest -> | |
let sell = List.fold rest ~init:buy ~f:max in | |
calculate_profit (max (sell - buy) profit) rest | |
in | |
calculate_profit 0 indices | |
;; | |
let%expect_test "max profit" = | |
let indices = [ 7; 1; 5; 3; 6; 4 ] in | |
let profit = max_profit indices in | |
printf "%d\n" profit; | |
[%expect {| 5 |}] | |
;; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment