Skip to content

Instantly share code, notes, and snippets.

@RP-3
Created August 16, 2020 07:44
Show Gist options
  • Select an option

  • Save RP-3/60a2ba79af4eee8c9b44be6397d5f044 to your computer and use it in GitHub Desktop.

Select an option

Save RP-3/60a2ba79af4eee8c9b44be6397d5f044 to your computer and use it in GitHub Desktop.
func max(a, b int) int {
if a > b {
return a
}
return b
}
func min(a, b int) int {
if a < b {
return a
}
return b
}
func maxProfit(prices []int) int {
if len(prices) <= 1 { // no trade possible
return 0
}
pFirstSellBy := make([]int, len(prices))
minSoFar := prices[0]
// do a single pass from left to right, to work out what the max profit
// is by selling on or before pFirstSellBy[i]
for i := 1; i < len(prices); i++ {
pFirstSellBy[i] = max(pFirstSellBy[i-1], prices[i]-minSoFar)
minSoFar = min(minSoFar, prices[i])
}
pSecondSellAfter := pFirstSellBy[len(pFirstSellBy)-1]
maxInFuture, maxProfitFromSecondTrx := prices[len(prices)-1], 0
// do another pass to work out what the max profit is from selling before
// pFirstSellBy[i-1], AND buying on day i and selling in the future
for i := len(prices) - 2; i > 0; i-- {
maxProfitFromSecondTrx = max(maxProfitFromSecondTrx, maxInFuture-prices[i])
maxInFuture = max(maxInFuture, prices[i])
pSecondSellAfter = max(pSecondSellAfter, pFirstSellBy[i-1]+maxProfitFromSecondTrx)
}
return result
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment