Skip to content

Add "Best Time to Buy and Sell Stock" #24

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 33 additions & 0 deletions lib/dynamic_programming/best_time_to_buy_and_sell_stock.ex
Original file line number Diff line number Diff line change
@@ -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
15 changes: 15 additions & 0 deletions test/dynamic_programming/best_time_to_buy_and_sell_stock_test.exs
Original file line number Diff line number Diff line change
@@ -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