mirror of
https://github.com/cubixle/codekata-golang.git
synced 2026-04-30 14:58:44 +01:00
20201106: partition array for max sum
This commit is contained in:
@@ -0,0 +1,28 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"math"
|
||||||
|
)
|
||||||
|
|
||||||
|
var arr = []int{1, 40, 24, 22, 12, 4, 5, 10, 62, 9, 55, 14, 39, 89}
|
||||||
|
|
||||||
|
func main() {
|
||||||
|
fmt.Println("solution:", findMaxSum(4, arr))
|
||||||
|
}
|
||||||
|
|
||||||
|
func findMaxSum(k int, arr []int) int {
|
||||||
|
l := len(arr)
|
||||||
|
dp := make([]int, l+1)
|
||||||
|
dp[0] = 0
|
||||||
|
for i := 0; i <= l; i++ {
|
||||||
|
max := -1
|
||||||
|
|
||||||
|
for j := 1; j <= k && i-j >= 0; j++ {
|
||||||
|
max = int(math.Max(float64(max), float64(arr[i-j])))
|
||||||
|
dp[i] = int(math.Max(float64(dp[i]), float64(dp[i-j]+max*j)))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
fmt.Println(dp)
|
||||||
|
return dp[l]
|
||||||
|
}
|
||||||
@@ -0,0 +1,40 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
func Test_findMax(t *testing.T) {
|
||||||
|
type args struct {
|
||||||
|
k int
|
||||||
|
arr []int
|
||||||
|
}
|
||||||
|
tests := []struct {
|
||||||
|
name string
|
||||||
|
args args
|
||||||
|
want int
|
||||||
|
}{
|
||||||
|
{
|
||||||
|
"example_1",
|
||||||
|
args{3, []int{1, 15, 7, 9, 2, 5, 10}},
|
||||||
|
84,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"example_2",
|
||||||
|
args{4, []int{1, 4, 1, 5, 7, 3, 6, 1, 9, 9, 3}},
|
||||||
|
83,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"example_3",
|
||||||
|
args{1, []int{1}},
|
||||||
|
1,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
for _, tt := range tests {
|
||||||
|
t.Run(tt.name, func(t *testing.T) {
|
||||||
|
if got := findMaxSum(tt.args.k, tt.args.arr); got != tt.want {
|
||||||
|
t.Errorf("findMaxSum() = %v, want %v", got, tt.want)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user