Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -1,28 +1,45 @@
# [3381.Maximum Subarray Sum With Length Divisible by K][title]

> [!WARNING|style:flat]
> This question is temporarily unanswered if you have good ideas. Welcome to [Create Pull Request PR](https://github.com/kylesliu/awesome-golang-algorithm)

## Description
You are given an array of integers `nums` and an integer `k`.

Return the **maximum** sum of a subarray of `nums`, such that the size of the subarray is **divisible** by `k`.

**Example 1:**

```
Input: a = "11", b = "1"
Output: "100"
Input: nums = [1,2], k = 1

Output: 3

Explanation:

The subarray [1, 2] with sum 3 has length equal to 2 which is divisible by 1.
```

**Example 2:**

```
Input: nums = [-1,-2,-3,-4,-5], k = 4

Output: -10

## 题意
> ...
Explanation:

The maximum sum subarray is [-1, -2, -3, -4] which has length equal to 4 which is divisible by 4.
```

## 题解
**Example 3:**

### 思路1
> ...
Maximum Subarray Sum With Length Divisible by K
```go
```
Input: nums = [-5,1,2,-3,4], k = 2

Output: 4

Explanation:

The maximum sum subarray is [1, 2, -3, 4] which has length equal to 4 which is divisible by 2.
```

## 结语

Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,24 @@
package Solution

func Solution(x bool) bool {
return x
import "math"

func Solution(nums []int, k int) int64 {
n := len(nums)
prefixSum := int64(0)
maxSum := int64(math.MinInt64)
kSum := make([]int64, k)
for i := range k {
kSum[i] = math.MaxInt64 / 2
}
kSum[k-1] = 0
for i := range n {
prefixSum += int64(nums[i])
if prefixSum-kSum[i%k] > maxSum {
maxSum = prefixSum - kSum[i%k]
}
if prefixSum < kSum[i%k] {
kSum[i%k] = prefixSum
}
}
return maxSum
}
Original file line number Diff line number Diff line change
Expand Up @@ -10,30 +10,31 @@ func TestSolution(t *testing.T) {
// 测试用例
cases := []struct {
name string
inputs bool
expect bool
inputs []int
k int
expect int64
}{
{"TestCase", true, true},
{"TestCase", true, true},
{"TestCase", false, false},
{"TestCase1", []int{1, 2}, 1, 3},
{"TestCase2", []int{-1, -2, -3, -4, -5}, 4, -10},
{"TestCase3", []int{-5, 1, 2, -3, 4}, 2, 4},
}

// 开始测试
for i, c := range cases {
t.Run(c.name+" "+strconv.Itoa(i), func(t *testing.T) {
got := Solution(c.inputs)
got := Solution(c.inputs, c.k)
if !reflect.DeepEqual(got, c.expect) {
t.Fatalf("expected: %v, but got: %v, with inputs: %v",
c.expect, got, c.inputs)
t.Fatalf("expected: %v, but got: %v, with inputs: %v %v",
c.expect, got, c.inputs, c.k)
}
})
}
}

// 压力测试
// 压力测试
func BenchmarkSolution(b *testing.B) {
}

// 使用案列
// 使用案列
func ExampleSolution() {
}
Loading