go: add «689. Maximum Sum of 3 Non-Overlapping Subarrays»

URL:	https://leetcode.com/problems/maximum-sum-of-3-non-overlapping-subarrays/
Signed-off-by: Matej Focko <me@mfocko.xyz>
This commit is contained in:
Matej Focko 2024-12-29 00:22:57 +01:00
parent 945eef30d1
commit 10d0ed1865
Signed by: mfocko
SSH key fingerprint: SHA256:icm0fIOSJUpy5+1x23sfr+hLtF9UhY8VpMC7H4WFJP8

View file

@ -0,0 +1,47 @@
package main
type Solution struct {
Sum int
Index int
}
func (s *Solution) Update(previous *Solution, sum, index int) {
if sum > previous.Sum {
s.Sum = sum
s.Index = index
return
}
s.Sum = previous.Sum
s.Index = previous.Index
}
func maxSumOfThreeSubarrays(nums []int, k int) []int {
n := len(nums)
prefix := make([]int, n+1)
for i := 1; i <= n; i++ {
prefix[i] = prefix[i-1] + nums[i-1]
}
best := make([][]Solution, 4)
for i, _ := range best {
best[i] = make([]Solution, n+1)
}
for subarrays := 1; subarrays <= 3; subarrays++ {
for end := k * subarrays; end <= n; end++ {
current := prefix[end] - prefix[end-k] + best[subarrays-1][end-k].Sum
best[subarrays][end].Update(&best[subarrays][end-1], current, end-k)
}
}
result := make([]int, 3)
end := n
for index := 3; index >= 1; index-- {
result[index-1] = best[index][end].Index
end = result[index-1]
}
return result
}