Skip to content
This repository was archived by the owner on Sep 20, 2023. It is now read-only.

Commit 57b7502

Browse files
committed
1031 accepted. 4ms, faster than 60.71%
1 parent 8e0d5f2 commit 57b7502

File tree

2 files changed

+106
-1
lines changed

2 files changed

+106
-1
lines changed
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,70 @@
11
package problem1031
22

3+
import "sort"
4+
35
func maxSumTwoNoOverlap(A []int, L int, M int) int {
6+
ls, ms := sums(A, L), sums(A, M)
7+
lSize, mSize := len(ls), len(ms)
8+
res := 0
9+
for i := 0; i < lSize; i++ {
10+
if ls[i].sum+ms[0].sum <= res {
11+
break
12+
}
13+
j := 0
14+
for j < mSize && ls[i].isOverlapping(ms[j]) {
15+
j++
16+
}
17+
if j < mSize {
18+
res = max(res, ls[i].sum+ms[j].sum)
19+
}
20+
}
21+
return res
22+
}
23+
24+
type entry struct {
25+
sum, left, right int
26+
}
27+
28+
func (e *entry) isOverlapping(other *entry) bool {
29+
return max(e.left, other.left) <= min(e.right, other.right)
30+
}
31+
32+
func sums(A []int, l int) []*entry {
33+
n := len(A)
34+
res := make([]*entry, n-l+1)
35+
sum := 0
36+
for i := 0; i < l; i++ {
37+
sum += A[i]
38+
}
39+
for i := l; i < n; i++ {
40+
res[i-l] = &entry{
41+
sum: sum,
42+
left: i - l,
43+
right: i - 1,
44+
}
45+
sum += A[i] - A[i-l]
46+
}
47+
res[n-l] = &entry{
48+
sum: sum,
49+
left: n - l,
50+
right: n - 1,
51+
}
52+
sort.Slice(res, func(i int, j int) bool {
53+
return res[i].sum > res[j].sum
54+
})
55+
return res
56+
}
57+
58+
func max(a, b int) int {
59+
if a > b {
60+
return a
61+
}
62+
return b
63+
}
464

5-
return 0
65+
func min(a, b int) int {
66+
if a < b {
67+
return a
68+
}
69+
return b
670
}

Algorithms/1031.maximum-sum-of-two-non-overlapping-subarrays/maximum-sum-of-two-non-overlapping-subarrays_test.go

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
package problem1031
22

33
import (
4+
"reflect"
45
"testing"
56

67
"github.com/stretchr/testify/assert"
@@ -14,6 +15,13 @@ var tcs = []struct {
1415
ans int
1516
}{
1617

18+
{
19+
[]int{4, 5, 14, 16, 16, 20, 7, 13, 8, 15},
20+
3,
21+
5,
22+
109,
23+
},
24+
1725
{
1826
[]int{0, 6, 5, 2, 2, 5, 1, 9, 4},
1927
1,
@@ -53,3 +61,36 @@ func Benchmark_maxSumTwoNoOverlap(b *testing.B) {
5361
}
5462
}
5563
}
64+
65+
func Test_sums(t *testing.T) {
66+
type args struct {
67+
A []int
68+
l int
69+
}
70+
tests := []struct {
71+
name string
72+
args args
73+
want []*entry
74+
}{
75+
{
76+
"test",
77+
args{
78+
A: []int{0, 1, 2, 3},
79+
l: 3,
80+
},
81+
[]*entry{
82+
&entry{6, 1, 3},
83+
&entry{3, 0, 2},
84+
},
85+
},
86+
87+
// TODO: Add test cases.
88+
}
89+
for _, tt := range tests {
90+
t.Run(tt.name, func(t *testing.T) {
91+
if got := sums(tt.args.A, tt.args.l); !reflect.DeepEqual(got, tt.want) {
92+
t.Errorf("sums() = %v, want %v", got, tt.want)
93+
}
94+
})
95+
}
96+
}

0 commit comments

Comments
 (0)