Created
July 27, 2024 10:04
-
-
Save idfumg/e95fc14aaab43280a2a03f1e514d0797 to your computer and use it in GitHub Desktop.
This file contains 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
const ( | |
INF = int(1e9) | |
) | |
var ( | |
cache [100001][2]int | |
) | |
func maxProfit(nums []int) int { | |
initCache(len(nums), -1) | |
return run(nums, 0, 0) | |
} | |
func initCache(N int, val int) { | |
for i := range N { | |
cache[i][0] = val | |
cache[i][1] = val | |
} | |
} | |
func run(nums []int, idx int, taken int) int { | |
N := len(nums) | |
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(nums, idx + 1, 1), | |
nums[idx], | |
) | |
return cache[idx][taken] | |
} | |
cache[idx][taken] = max( | |
run(nums, idx + 1, 0), | |
-nums[idx] + run(nums, 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