Last active
March 29, 2020 09:22
-
-
Save mAlishera/63f1a3dba34c61359e1706158510ad9d to your computer and use it in GitHub Desktop.
find max profit (min loss) to buy and sell within one day stocks prices (Kadane's algo)
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
def find_buy_sell_stock_prices(array) | |
return if !array || !array[1] | |
c_buy, g_sell, g_profit, c_profit = array[0], array[1], (array[1] - array[0]), 0 | |
i = 1 | |
while i < array.size | |
c_profit = array[i] - c_buy | |
if c_profit > g_profit | |
g_profit = c_profit | |
g_sell = array[i] | |
end | |
c_buy = array[i] if (array[i] < c_buy) | |
i += 1 | |
end | |
[g_sell - g_profit, g_sell] | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment