diff options
author | terminaldweller <thabogre@gmail.com> | 2022-12-23 05:57:55 +0000 |
---|---|---|
committer | terminaldweller <thabogre@gmail.com> | 2022-12-23 05:57:55 +0000 |
commit | 6c3b2e92d32d482ac510c12abb12ac5d2b2a9bcd (patch) | |
tree | 423037e346df979e91a2a52f81c6834359f523f0 /309 | |
parent | 834 (diff) | |
download | leetcode-6c3b2e92d32d482ac510c12abb12ac5d2b2a9bcd.tar.gz leetcode-6c3b2e92d32d482ac510c12abb12ac5d2b2a9bcd.zip |
309
Diffstat (limited to '309')
-rw-r--r-- | 309/go.mod | 3 | ||||
-rw-r--r-- | 309/main.go | 43 |
2 files changed, 46 insertions, 0 deletions
diff --git a/309/go.mod b/309/go.mod new file mode 100644 index 0000000..fb02871 --- /dev/null +++ b/309/go.mod @@ -0,0 +1,3 @@ +module 309 + +go 1.19 diff --git a/309/main.go b/309/main.go new file mode 100644 index 0000000..e1b5dfb --- /dev/null +++ b/309/main.go @@ -0,0 +1,43 @@ +package main + +import "fmt" + +func maxProfit(prices []int) int { + l := len(prices) + if l < 2 { + return 0 + } + + has1_doNothing := -prices[0] + has1_Sell := 0 + has0_DoNothing := 0 + has0_Buy := -prices[0] + + for i := range prices { + if has1_doNothing > has0_Buy { + has1_doNothing = +has1_doNothing + } else { + has1_doNothing = +has0_Buy + } + // has1_doNothing = has1_doNothing > has0_Buy ? has1_doNothing : has0_Buy + has0_Buy = -prices[i] + has0_DoNothing + if has0_DoNothing > has1_Sell { + has0_DoNothing = +has0_DoNothing + } else { + has0_DoNothing = +has1_Sell + } + // has0_DoNothing = has0_DoNothing > has1_Sell ? has0_DoNothing : has1_Sell + has1_Sell = prices[i] + has1_doNothing + } + + if has1_Sell > has0_DoNothing { + return has1_Sell + } else { + return has0_DoNothing + } +} + +func main() { + fmt.Println(maxProfit([]int{1, 2, 3, 0, 2})) + fmt.Println(maxProfit([]int{1})) +} |