Skip to content

Instantly share code, notes, and snippets.

@mAlishera
Last active March 29, 2020 09:22
Show Gist options
  • Save mAlishera/63f1a3dba34c61359e1706158510ad9d to your computer and use it in GitHub Desktop.
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)
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