Skip to content

Instantly share code, notes, and snippets.

@idfumg
Created July 27, 2024 10:05
Show Gist options
  • Save idfumg/cdae8a155e8b9a8da633f993fe5c5e53 to your computer and use it in GitHub Desktop.
Save idfumg/cdae8a155e8b9a8da633f993fe5c5e53 to your computer and use it in GitHub Desktop.
const (
INF = int(1e9)
)
var (
cache [100001][2]int
nums [100001]int
N int
)
func maxProfit(prices []int) int {
init_all(prices)
return run(0, 0)
}
func init_all(prices []int) {
N = len(prices)
for i := range prices {
cache[i][0] = -1
cache[i][1] = -1
nums[i] = prices[i]
}
}
func run(idx int, taken int) int {
if idx == N && taken == 1 {
return -INF
}
if idx == N && taken == 0 {
return 0
}
if cache[idx][taken] != -1 {
return cache[idx][taken]
}
if taken == 1 {
cache[idx][taken] = max(
run(idx + 1, 1),
nums[idx],
)
return cache[idx][taken]
}
cache[idx][taken] = max(
run(idx + 1, 0),
-nums[idx] + run(idx + 1, 1),
)
return cache[idx][taken]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment