-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathproblem049.go
More file actions
29 lines (26 loc) · 844 Bytes
/
Copy pathproblem049.go
File metadata and controls
29 lines (26 loc) · 844 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
package problem049
func MaximizeContiguousSum(values []int) int {
// ex) [10, 20, -50, 24, 1, -10, 20, -6] => [10, 20, -50] [24, 1, -10, 20] [-6]
totalSum := 0
for _, value := range values {
totalSum += value
}
leftExcludedMinSum, leftExcludedSum, leftExcludedEndsAt := 0, 0, 0
rightExcludedMinSum, rightExcludedSum, rightExcludedStartsAt := totalSum, totalSum, 0
for i := range values {
if leftExcludedSum += values[i]; leftExcludedSum < leftExcludedMinSum {
leftExcludedEndsAt = i + 1
}
if rightExcludedSum -= values[i]; rightExcludedSum < rightExcludedMinSum {
rightExcludedStartsAt = i + 1
}
}
if leftExcludedEndsAt >= rightExcludedStartsAt {
return 0
}
maxContiguousSum := 0
for _, value := range values[leftExcludedEndsAt:rightExcludedStartsAt] {
maxContiguousSum += value
}
return maxContiguousSum
}