diff --git a/lib/dynamic_programming/best_time_to_buy_and_sell_stock.ex b/lib/dynamic_programming/best_time_to_buy_and_sell_stock.ex new file mode 100644 index 0000000..1fa9bf9 --- /dev/null +++ b/lib/dynamic_programming/best_time_to_buy_and_sell_stock.ex @@ -0,0 +1,33 @@ +defmodule Algorithms.DynamicProgramming.BestTimeToBuyStock do + @moduledoc """ + Best Time To Buy and Sell Stock + """ + + @doc """ + You are given an array prices where prices[i] is the price of a given stock on the ith day. + You want to maximize your profit by choosing a single day to buy one stock and choosing a different day in the future to sell that stock. + Return the maximum profit you can achieve from this transaction. If you cannot achieve any profit, return 0. + + https://leetcode.com/problems/best-time-to-buy-and-sell-stock/description/ + """ + @spec max_profit(prices :: [integer]) :: integer + def max_profit(prices) do + [first_price | remaining] = prices + + {_, stack} = + Enum.reduce(remaining, {first_price, []}, fn current, {base, stack} -> + res = current - base + + if res > 0 do + {base, [res | stack]} + else + {current, stack} + end + end) + + case stack do + [] -> 0 + _ -> Enum.max(stack) + end + end +end diff --git a/test/dynamic_programming/best_time_to_buy_and_sell_stock_test.exs b/test/dynamic_programming/best_time_to_buy_and_sell_stock_test.exs new file mode 100644 index 0000000..e507bbc --- /dev/null +++ b/test/dynamic_programming/best_time_to_buy_and_sell_stock_test.exs @@ -0,0 +1,15 @@ +defmodule Algorithms.DynamicProgramming.BestTimeToBuyStockTest do + alias Algorithms.DynamicProgramming.BestTimeToBuyStock + + use ExUnit.Case + + describe "max_profit/1 - example test cases" do + test "max_profit 1" do + assert BestTimeToBuyStock.max_profit([7, 1, 5, 3, 6, 4]) == 5 + end + + test "max_profit 2" do + assert BestTimeToBuyStock.max_profit([7, 6, 4, 3, 1]) == 0 + end + end +end