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:
parent
945eef30d1
commit
10d0ed1865
1 changed files with 47 additions and 0 deletions
47
go/maximum-sum-of-3-non-overlapping-subarrays.go
Normal file
47
go/maximum-sum-of-3-non-overlapping-subarrays.go
Normal 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
|
||||
}
|
Loading…
Reference in a new issue