Skip to content

Instantly share code, notes, and snippets.

@keturiosakys
Last active July 24, 2023 11:06
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 keturiosakys/ef0d54563dc1cc728c902f1ea7b875f1 to your computer and use it in GitHub Desktop.
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.
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